// src/bin/main.rs
#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_time::{Duration, Timer};
use embassy_stm32::bind_interrupts;
use embassy_stm32::peripherals;
use embassy_stm32::usart::{BufferedInterruptHandler, BufferedUart, Config};
use embedded_io_async::{Read, Write};
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};

// Select + channel + heapless Vec
use embassy_futures::select::{select, Either};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use heapless::Vec;

const MAX_MSG: usize = 64;
const QSIZE: usize = 4;
static UART_TX: Channel<CriticalSectionRawMutex, Vec<u8, MAX_MSG>, QSIZE> = Channel::new();

bind_interrupts!(
    struct Irqs {
        USART1 => BufferedInterruptHandler<peripherals::USART1>;
    }
);

#[embassy_executor::task]
async fn uart_task(mut uart: BufferedUart<'static>) {
    let mut buf = [0u8; 1];

    loop {
        let rx_fut = uart.read(&mut buf);
        let tx_fut = UART_TX.receive();

        match select(rx_fut, tx_fut).await {
            // Incoming RX byte
            Either::First(res) => {
                if let Ok(_) = res {
                    // Echo and log
                    unwrap!(uart.write(&buf).await);
                    unwrap!(uart.write(b"a\r\n").await);
                    info!("uart received {}", buf[0]);
                    unwrap!(uart.flush().await);
                }
            }
            // Outgoing TX request from main
            Either::Second(msg) => {
                unwrap!(uart.write(&msg).await);
                unwrap!(uart.flush().await);
                info!("sent {} bytes", msg.len());
            }
        }
    }
}

pub async fn send_uart(data: &[u8]) {
    let mut v: Vec<u8, MAX_MSG> = Vec::new();
    // TODO truncation nonsense as a temp solution
    let _ = v.extend_from_slice(data);
    UART_TX.send(v).await;
}

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    info!("tititititi");
    let p = embassy_stm32::init(Default::default());

    static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    let tx_buf = TX_BUF.init([0; 256]);
    let rx_buf = RX_BUF.init([0; 256]);

    let mut cfg = Config::default();
    cfg.baudrate = 230_400;

    let usart = BufferedUart::new(
        p.USART1,
        p.PA10, // RX
        p.PA9,  // TX
        tx_buf,
        rx_buf,
        Irqs,
        cfg,
    )
    .unwrap();

    info!("starting uart task");
    spawner.spawn(uart_task(usart)).unwrap();

    let mut counter: u32 = 230;
    loop {
        counter = counter.wrapping_add(1);

        if counter % 10000 == 0 {
            info!("CPU doing other work: {}", counter);
        }
        if counter % 100000 == 0 {
            // Send whenever you want; the UART task performs the actual write.
            send_uart(b"Hello\r\n").await;
        }
        // Timer::after(Duration::from_micros(1)).await;
    }
}
