use bme280::spi::BME280;
use embedded_hal::digital::v2::OutputPin;
use mkl25z4_hal::time::CopyableMonoTimer;

use super::pins::{BME280Pins, DisplayBmeSpi};

pub fn bme280(
    mut pins: BME280Pins,
    spi: DisplayBmeSpi,
    delay: CopyableMonoTimer,
) -> (BME280Pins, DisplayBmeSpi, BME280Data) {
    // Enable power.
    pins.pwr.set_low().ok();

    // Read the sensor.
    let mut bme = BME280::new(spi, pins.cs, delay).unwrap();
    bme.init().unwrap();
    let values = bme.measure().unwrap();
    let (spi, cs, _) = bme.destroy();

    // Disable power again.
    pins.pwr.set_high().ok();
    (
        BME280Pins {
            pwr: pins.pwr,
            cs: cs,
        },
        spi,
        BME280Data {
            temperature: (values.temperature * 10.0) as i32,
            humidity: (values.humidity * 100.0) as u32,
            pressure: values.pressure as u32,
        },
    )
}

#[derive(Clone, Copy)]
pub struct BME280Data {
    pub temperature: i32,
    pub humidity: u32,
    pub pressure: u32,
}
