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

use defmt::*;
use embassy_stm32::usart::{Config, Uart};
use embassy_time::{Duration, Timer};
use embassy_sync::channel::Channel;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;

use {defmt_rtt as _, panic_probe as _};

static PIPE: Channel<CriticalSectionRawMutex, u8, 64> = Channel::new();

#[cortex_m_rt::entry]
fn main() -> ! {
    info!("tititititi");

    let p = embassy_stm32::init(Default::default());

    let config = Config::default();
    let mut usart = Uart::new_blocking(p.USART1, p.PA10, p.PA9, config).unwrap();

    let sender = PIPE.sender();
    let receiver = PIPE.receiver();

    info!("starting echo");

    let mut buf = [0u8; 1];
    let mut send_allowed: bool = true;
    let mut rec_allowed: bool = true;
    loop {
        if usart.blocking_read(&mut buf).is_ok() {
            let byte = buf[0];
            match byte {
                0x11 => {
                    send_allowed = true;
                    info!("Vysielanie povolené");
                }
                0x13 => {
                    send_allowed = false;
                    info!("Vysielanie zakázané");
                }
                _ => {
                }
            }
        }

        while let Ok(stored_byte) = receiver.try_receive() {
            unwrap!(usart.blocking_write(&[stored_byte]));
            unwrap!(usart.blocking_write(b" (pipe)\r\n"));
        }
        if send_allowed {
            unwrap!(usart.blocking_write(&buf));
            unwrap!(usart.blocking_write(b"a\r\n"));
        } else {
            // let _ = sender.try_send(byte);
        }
        let _ = Timer::after(Duration::from_millis(100));
    }
}
