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

use defmt::*;
use embassy_executor::Spawner;
use embassy_time::Instant;
use embassy_executor::task;
use embassy_stm32::dma::Request;
use embassy_stm32::gpio::{Input, Output, Level, Pull, Speed};
use dma_gpio::software_uart::{
    dma_timer::{init_tim6_for_uart, init_tim7_for_uart},
    gpio_dma_uart_rx::rx_dma_task,
    debug::dump_tim6_regs,
};
use dma_gpio::config::{BAUD, RX_OVERSAMPLE, TX_OVERSAMPLE};
use dma_gpio::config::{TX_RING_BYTES, RX_RING_BYTES};
use dma_gpio::software_uart::gpio_dma_uart_tx::tx_dma_task;
use static_cell::StaticCell;
use embassy_futures::yield_now;
use dma_gpio::hw_uart_pc::usart1;
use dma_gpio::hw_uart_pc::driver::uart_task;
use embassy_stm32::usart::{BufferedUart, Config, BufferedInterruptHandler};
use embassy_stm32::peripherals;
use embassy_stm32::bind_interrupts;
use dma_gpio::config::{PIPE_HW_TX, PIPE_HW_RX, PIPE_SW_TX, PIPE_SW_RX};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, pipe::Pipe};
use {defmt_rtt as _, panic_probe as _};

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

// Software uart
pub const TIM6_UP_REQ: Request = 4;
static SW_TX_RING: StaticCell<[u32; TX_RING_BYTES]> = StaticCell::new();
static SW_RX_RING: StaticCell<[u8; RX_RING_BYTES]> = StaticCell::new();

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

    // HARDWARE UART to the PC
    let mut cfg = Config::default();
    cfg.baudrate = BAUD;
    static TX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    static RX_BUF: StaticCell<[u8; 256]> = StaticCell::new();
    let uart = BufferedUart::new(
        p.USART1,
        p.PA10, // RX pin
        p.PA9,  // TX pin
        TX_BUF.init([0; 256]),
        RX_BUF.init([0; 256]),
        Irqs,
        cfg,
    ).unwrap();
    let yield_period = usart1::setup_and_spawn(BAUD);
    spawner.spawn(uart_task(uart, &PIPE_HW_TX, &PIPE_HW_RX).unwrap());
    // END OF HARDWARE UART to the PC

    // SOFTWARE UART 
    let _rx = Input::new(p.PA3, Pull::Up);
    let _tx = Output::new(p.PA2, Level::High, Speed::VeryHigh);
    init_tim6_for_uart(p.TIM6, BAUD, TX_OVERSAMPLE);
    init_tim7_for_uart(p.TIM7, BAUD, RX_OVERSAMPLE);
    dump_tim6_regs();

    // Safe one-time init from StaticCell
    let sw_rx_ring: &mut [u8; RX_RING_BYTES] = SW_RX_RING.init([0; RX_RING_BYTES]);
    let sw_tx_ring: &mut [u32; TX_RING_BYTES] = SW_TX_RING.init([0; TX_RING_BYTES]);
    spawner.spawn(rx_dma_task(p.GPDMA1_CH1, sw_rx_ring, &PIPE_SW_RX).unwrap());

    // Create and start the TX DMA ring in main.
    let bsrr_ptr = embassy_stm32::pac::GPIOA.bsrr().as_ptr() as *mut u32;
    // let odr_ptr = embassy_stm32::pac::GPIOA.odr().as_ptr() as *mut u32; // NEEDS DECODE CHANGE
    spawner.spawn(tx_dma_task(p.GPDMA1_CH0, bsrr_ptr, sw_tx_ring, &PIPE_SW_TX).unwrap());
    // EDN OF SOFTWARE UART 


    // BRIDGE
    spawner.spawn(bridge_hw_to_sw(&PIPE_HW_RX, &PIPE_SW_TX).unwrap());
    spawner.spawn(bridge_sw_to_hw(&PIPE_SW_RX, &PIPE_HW_TX).unwrap());
    // END OF BRIDGE
    
    let mut last_yield = Instant::now();
    let mut buf = [0u8; 32];

    loop {
        info!("tick start");
        // Timer::after(Duration::from_millis(100)).await;
        // info!("tick end");

        let n1 = PIPE_HW_RX.read(&mut buf).await;
        if n1 > 0 {
            info!("PC received: {:a}", &buf[..n1]);
            let _ = PIPE_SW_TX.write(&buf[..n1]).await;
            info!("SW UART TX sent echo: {:a}", &buf[..n1]);
        }
        yield_now().await;

        let n2 = PIPE_SW_RX.read(&mut buf).await;
        if n2 > 0 {
            info!("SW UART RX received: {:a}", &buf[..n2]);
        }

        if Instant::now().duration_since(last_yield) >= yield_period {
            yield_now().await;
            last_yield = Instant::now();
        }

    }
}

#[task]
pub async fn bridge_hw_to_sw(
    hw_rx: &'static Pipe<CriticalSectionRawMutex, 1024>,
    sw_tx: &'static Pipe<CriticalSectionRawMutex, 1024>,
) {
    let mut buf = [0u8; 64];
    loop {
        let n = hw_rx.read(&mut buf).await;
        if n > 0 {
            let _ = sw_tx.write(&buf[..n]).await;
        }
    }
}

#[task]
pub async fn bridge_sw_to_hw(
    sw_rx: &'static Pipe<CriticalSectionRawMutex, 1024>,
    hw_tx: &'static Pipe<CriticalSectionRawMutex, 1024>,
) {
    let mut buf = [0u8; 64];
    loop {
        let n = sw_rx.read(&mut buf).await;
        if n > 0 {
            let _ = hw_tx.write(&buf[..n]).await;
        }
    }
}
