#pragma once

#include <zephyr/drivers/i2c.h>

#define BH1750_POWER_DOWN 0x00                  // No active state
#define BH1750_POWER_ON 0x01                    // Waiting for measurement command
#define BH1750_RESET 0x07                       // Reset data register value - not accepted in POWER_DOWN mode
#define BH1750_DEFAULT_MTREG 69                 // Default MTreg value
#define BH1750_MTREG_MIN 31
#define BH1750_MTREG_MAX 254

#define I2C0_BH1750 DT_NODELABEL(bh1750)

static const struct i2c_dt_spec dev_bh1750 = I2C_DT_SPEC_GET(I2C0_BH1750);

uint8_t bh1750_regs[2] ={0x21,0x00};
uint8_t temp_reading_bh1750[2]= {0};

enum Mode {
    // same as Power Down
    UNCONFIGURED = 0,
    // Measurement at 1 lux resolution. Measurement time is approx 120ms.
    CONTINUOUS_HIGH_RES_MODE = 0x10,
    // Measurement at 0.5 lux resolution. Measurement time is approx 120ms.
    CONTINUOUS_HIGH_RES_MODE_2 = 0x11,
    // Measurement at 4 lux resolution. Measurement time is approx 16ms.
    CONTINUOUS_LOW_RES_MODE = 0x13,
    // Measurement at 1 lux resolution. Measurement time is approx 120ms.
    ONE_TIME_HIGH_RES_MODE = 0x20,
    // Measurement at 0.5 lux resolution. Measurement time is approx 120ms.
    ONE_TIME_HIGH_RES_MODE_2 = 0x21,
    // Measurement at 4 lux resolution. Measurement time is approx 16ms.
    ONE_TIME_LOW_RES_MODE = 0x23
};

//bool begin(Mode mode = CONTINUOUS_HIGH_RES_MODE, byte addr = 0x23, TwoWire* i2c = nullptr);
//bool configure(Mode mode);
//bool setMTreg(byte MTreg);
//bool measurementReady(bool maxWait = false);
//float readLightLevel();

double measure_bh1750(){
    int ret = i2c_write_read_dt(&dev_bh1750,&bh1750_regs[0],1,&temp_reading_bh1750,2);

	uint16_t raw_value = ((uint16_t) temp_reading_bh1750[0] << 8) | (uint16_t) temp_reading_bh1750[1];
	double illuminance = (raw_value)/1.2;

	if(ret != 0){
		printk("Failed to read I2C device address %x at Reg. %x \n", dev_bh1750.addr,bh1750_regs[0]);
	}else{

		printk("Illuminance: %.2f lx\n", illuminance);
	}

    return illuminance;
}

// Correction factor used to calculate lux. Typical value is 1.2 but can
// range from 0.96 to 1.44. See the data sheet (p.2, Measurement Accuracy)
//const float BH1750_CONV_FACTOR = 1.2;