use esp_idf_hal::i2c::*;
use esp_idf_hal::prelude::*;
use esp_idf_hal::delay::FreeRtos;
use esp_idf_hal::peripherals::Peripherals;

use std::sync::{Arc, Mutex};

mod lcd;

const WIDTH: i32 = 20;

pub struct Point {
    pub x: i32,
    pub y: i32,
}

impl Point {
    pub fn new(x: i32, y: i32) -> Self {
        Self {
            x,
            y,
        }
    }
}

pub fn draw_text(config: &mut I2cDriver, position: Point, text: &str, centered: bool) {
    let _ = match centered {
        true => lcd::set_cursor(config, get_centered(text.into()) as u8, position.y as usize),
        false => lcd::set_cursor(config, position.x as u8, position.y as usize),
    };

    let _ = lcd::print_str(config, text);
}

fn get_centered(text: String) -> i32 {
    let val = (20 - text.len()) / 2;

    dbg!(val);

    val.try_into().unwrap()
}

fn main() -> anyhow::Result<()> {
    let peripherals = Peripherals::take().unwrap();
    let i2c = peripherals.i2c0;
    let sda = peripherals.pins.gpio6;
    let scl = peripherals.pins.gpio5;

    let config = I2cConfig::new().baudrate(100.kHz().into());
    let mut i2c = I2cDriver::new(i2c, sda, scl, &config)?;

    let _ = lcd::init(&mut i2c);
    let _ = lcd::backlight(&mut i2c);

    draw_text(&mut i2c, Point::new(4, 1), "12:43", true);
    draw_text(&mut i2c, Point::new(0, 2), "Thu 8 June", true);

    loop {}
}