#pragma once

#include <zephyr/zephyr.h>
#include <zephyr/sys/printk.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/drivers/sensor/mhz19b.h>

const struct device *mhz19b_dev;
struct sensor_value mhz19b_val;

void mhz19b_init(void)
{
	
	int ret;

	printk("Winsen MH-Z19B CO2 sensor:\n");

	mhz19b_dev = DEVICE_DT_GET_ONE(winsen_mhz19b);
	if (!device_is_ready(mhz19b_dev)) {
		printk("MH-Z19B: device not found.\n");
		return;
	}

	printk("Configuring sensor - ");

	mhz19b_val.val1 = 5000;
	ret = sensor_attr_set(mhz19b_dev, SENSOR_CHAN_CO2, SENSOR_ATTR_FULL_SCALE, &mhz19b_val);
	if (ret != 0) {
		printk("failed to set range to %d\n", mhz19b_val.val1);
		return;
	}

	mhz19b_val.val1 = 1;
	ret = sensor_attr_set(mhz19b_dev, SENSOR_CHAN_CO2, SENSOR_ATTR_MHZ19B_ABC, &mhz19b_val);
	if (ret != 0) {
		printk("failed to set ABC to %d\n", mhz19b_val.val1);
		return;
	}

	printk("OK\n");

	printk("Reading configurations from MH-Z19B:\n");

	ret = sensor_attr_get(mhz19b_dev, SENSOR_CHAN_CO2, SENSOR_ATTR_FULL_SCALE, &mhz19b_val);
	if (ret != 0) {
		printk("failed to get range\n");
		return;
	}

	printk("Sensor range is set to %dppm\n", mhz19b_val.val1);

	ret = sensor_attr_get(mhz19b_dev, SENSOR_CHAN_CO2, SENSOR_ATTR_MHZ19B_ABC, &mhz19b_val);
	if (ret != 0) {
		printk("failed to get ABC\n");
		return;
	}

	printk("Sensor ABC is %s\n", mhz19b_val.val1 == 1 ? "enabled" : "disabled");
}

int32_t mhz19b_measure_co2(void){
	if (sensor_sample_fetch(mhz19b_dev) != 0) {
		printk("MH-Z19B: sample fetch fail.\n");
		return;
	}

	if (sensor_channel_get(mhz19b_dev, SENSOR_CHAN_CO2, &mhz19b_val) != 0) {
		printk("MH-Z19B: channel get fail.\n");
		return;
	}

	printk("CO2: %d ppm\n", mhz19b_val.val1);
	return mhz19b_val.val1;
}
