// src/hw_uart_pc/init.rs

use crate::config::{BAUD, PIPE_HW_TX, PIPE_HW_RX};
use crate::hw_uart_pc::driver::uart_task;
use crate::logic::uart_cmd::uart_cmd_task;
use static_cell::StaticCell;
use embassy_stm32::usart::BufferedInterruptHandler;
use embassy_stm32::usart::{BufferedUart, Config as UsartConfig};
use embassy_stm32::peripherals;
use embassy_stm32::bind_interrupts;
use embassy_executor::Spawner;
use embassy_hal_internal::Peri;
use embassy_stm32::peripherals::{USART1, PA9, PA10};
use defmt::info;

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

pub fn init_hw_uart_to_pc(
    usart1: Peri<'static, USART1>,
    pa10: Peri<'static, PA10>,
    pa9: Peri<'static, PA9>,
    spawner: &Spawner,
) {
    let mut cfg = UsartConfig::default();
    cfg.baudrate = BAUD;

    static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();

    let uart = BufferedUart::new(
        usart1,
        pa10, // RX pin
        pa9,  // TX pin
        TX_BUF.init([0; 256]),
        RX_BUF.init([0; 256]),
        Irqs,
        cfg,
    )
    .unwrap();

    spawner.spawn(uart_task(uart, &PIPE_HW_TX, &PIPE_HW_RX).unwrap());
    spawner.spawn(uart_cmd_task().unwrap());

    info!("USART1 initialized @ {} bps", BAUD);
}
