// src/hw_uart_internal/driver.rs
use defmt::unwrap;
use embassy_futures::select::{select, Either};
use embassy_stm32::usart::BufferedUart;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::pipe::Pipe;
use embedded_io_async::{Read, Write};
use crate::hw_uart_pc::safety::{RX_PIPE_CAP, TX_PIPE_CAP};
use embassy_futures::yield_now;

#[embassy_executor::task]
pub async fn uart_task(
    mut uart: BufferedUart<'static>,
    tx_pipe: &'static Pipe<CriticalSectionRawMutex, TX_PIPE_CAP>,
    rx_pipe: &'static Pipe<CriticalSectionRawMutex, RX_PIPE_CAP>,
) {
    let mut rx_byte = [0u8; 1];
    let mut tx_buf = [0u8; 64];

    loop {
        let rx_fut = uart.read(&mut rx_byte);
        let tx_fut = async {
            let n = tx_pipe.read(&mut tx_buf).await;
            n
        };

        match select(rx_fut, tx_fut).await {
            // Incoming data from UART hardware
            Either::First(res) => {
                if let Ok(_) = res {
                    let _ = rx_pipe.write(&rx_byte).await;
                }
            }
            // Outgoing data waiting in TX pipe
            Either::Second(n) => {
                unwrap!(uart.write(&tx_buf[..n]).await);
            }
        }
        yield_now().await;
    }
}
