use bitflags::bitflags;
use embedded_hal::spi::SpiBus;

bitflags! {
    struct MCP3208_0: u8 {
        const START = 0b0000_0100; // start bit
        const SGL   = 0b0000_0010; // SGL (絶対値)
        const D2    = 0b0000_0001; // チャネル選択 (2ビット目)
    }
}

#[derive(Copy, Clone, Debug)]
pub enum Error<SPI> {
    Spi(SPI),
}

/// 0〜100%の範囲で、明るさを返す。
/// 大きい方が明るい。
pub fn brightness<SPI>(bus: &mut SPI) -> Result<f64, Error<SPI::Error>>
where
    SPI: SpiBus,
{
    let mut read_buf: [u8; 3] = [0; 3];
    let write_buf: [u8; 3] = [(MCP3208_0::START | MCP3208_0::SGL).bits, 0, 0];

    bu.transfer(&mut read_buf, &write_buf).map_err(Error::Spi)?;

    let val = ((read_buf[1] & 0b0000_1111) as u16) << 8 | read_buf[0] as u16;

    Ok(val as f64 / 4096.0_f64 * 100.0)
}
