#![allow(missing_docs)]
#![no_std]
#![no_main]

use core::{convert::Infallible, fmt};

use device_envoy_example_common::clock_ui::{run_clock_ui, ClockUiEvent};
use embassy_executor::Spawner;
use esp_backtrace as _;
use log::info;

use device_envoy_esp::{
    button::PressedTo,
    button_watch,
    clock_sync::{ClockSyncEsp, ClockSyncStaticEsp, ONE_SECOND},
    flash_block::FlashBlockEsp,
    init_and_start, lcd_text,
    lcd_text::LcdText as _,
    wifi_auto::{
        fields::{TimezoneField, TimezoneFieldStatic},
        WifiAuto as _, WifiAutoEsp, WifiAutoEvent,
    },
    Error, Result,
};

esp_bootloader_esp_idf::esp_app_desc!();

button_watch! {
    ForcePortalButtonWatch {
        pin: GPIO6,
    }
}

lcd_text! {
    i2c: I2C0,
    sda_pin: GPIO16,
    scl_pin: GPIO17,
    LcdTextClock {
        width: 16,
        height: 2,
        address: 0x27
    }
}

#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
    match inner_main(spawner).await {
        Ok(infallible) => match infallible {},
        Err(error) => panic!("{error:?}"),
    }
}

async fn inner_main(spawner: Spawner) -> Result<Infallible> {
    init_and_start!(p);
    esp_println::logger::init_logger(log::LevelFilter::Info);

    info!("Starting LCD clock with WiFi");

    let lcd_text_clock = LcdTextClock::new(p.I2C0, p.GPIO16, p.GPIO17, spawner)?;
    lcd_text_clock.write_text("Booting...\nLCD Clock");

    let [wifi_auto_flash_block, mut timezone_flash_block] = FlashBlockEsp::new_array::<2>(p.FLASH)?;

    static TIMEZONE_FIELD_STATIC: TimezoneFieldStatic = TimezoneField::new_static();
    let timezone_field = TimezoneField::new(&TIMEZONE_FIELD_STATIC, timezone_flash_block);
    let button_watch6 = ForcePortalButtonWatch::new(p.GPIO6, PressedTo::Ground, spawner).await?;

    let wifi_auto = WifiAutoEsp::new(
        p.WIFI,
        wifi_auto_flash_block,
        "DeviceEnvoyClock",
        [timezone_field],
        spawner,
    )?;

    let lcd_text_clock_ref = lcd_text_clock;
    let stack = wifi_auto
        .connect(&mut *button_watch6, |wifi_auto_event| {
            let lcd_text_clock_ref = lcd_text_clock_ref;
            async move {
                match wifi_auto_event {
                    WifiAutoEvent::CaptivePortalReady => {
                        lcd_text_clock_ref.write_text("Join WiFi:\nDeviceEnvoyClock");
                    }
                    WifiAutoEvent::Connecting { .. } => {
                        lcd_text_clock_ref.write_text("Connecting...\nPlease wait");
                    }
                    WifiAutoEvent::ConnectionFailed => {
                        lcd_text_clock_ref.write_text("WiFi failed\nRetry setup");
                    }
                }
                Ok(())
            }
        })
        .await?;

    let timezone_offset_minutes = timezone_field
        .offset_minutes()?
        .ok_or(Error::MissingCustomWifiAutoField)?;
    static CLOCK_SYNC_STATIC: ClockSyncStaticEsp = ClockSyncEsp::new_static();
    let clock_sync = ClockSyncEsp::new(
        &CLOCK_SYNC_STATIC,
        stack,
        timezone_offset_minutes,
        Some(ONE_SECOND),
        spawner,
    );

    info!("Entering main event loop");
    lcd_text_clock.write_text("WiFi connected\nWaiting NTP");

    let lcd_text_clock_ref = lcd_text_clock;
    run_clock_ui(
        &clock_sync,
        &mut *button_watch6,
        &mut timezone_flash_block,
        |clock_ui_event| async move {
            let text = event_text(clock_ui_event).map_err(|_| Error::FormatError)?;
            lcd_text_clock_ref.write_text(text.as_str());
            Ok(())
        },
    )
    .await
}

fn event_text(clock_ui_event: ClockUiEvent) -> Result<heapless::String<32>, fmt::Error> {
    let mut text = heapless::String::<32>::new();
    match clock_ui_event {
        ClockUiEvent::RenderHoursMinutes { hours, minutes } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:>2}:{:02} HH:MM\nshort for MM:SS", hours, minutes),
            )?;
        }
        ClockUiEvent::RenderMinutesSeconds { minutes, seconds } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:02}:{:02} MM:SS\nshort for FAST", minutes, seconds),
            )?;
        }
        ClockUiEvent::RenderHoursMinutesEdit { hours, minutes } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:>2}:{:02} TZ EDIT\nshort +1h long OK", hours, minutes),
            )?;
        }
    }
    Ok(text)
}
