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

use defmt::info;
use embassy_executor::Spawner;
use embassy_stm32::exti::ExtiInput;
use embassy_stm32::gpio;
use embassy_stm32::gpio::{Output, Pull};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::Duration;
use semestralka2::receive::bit_receive_and_decode;
use semestralka2::level_for_bit;
use semestralka2::send::Tx;
use semestralka2::send::{bit_send, msg_encode};

use {defmt_rtt as _, panic_probe as _};

static PIPE_SEND: Channel<CriticalSectionRawMutex, u8, 128> = Channel::new();
static PIPE_REC: Channel<CriticalSectionRawMutex, u8, 128> = Channel::new();
// static REC_ALLOWED: AtomicBool = AtomicBool::new(true);

#[embassy_executor::main]
async fn main(spawner: Spawner) {
    info!("tititititi");

    let p = embassy_stm32::init(Default::default());
    let tx = Output::new(
        p.PF2,
        if level_for_bit(1) {
            gpio::Level::High
        } else {
            gpio::Level::Low
        },
        gpio::Speed::VeryHigh,
    );
    let rx = ExtiInput::new(p.PA3, p.EXTI3, Pull::Up);

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

    let e_nrz = semestralka2::Encoding::Nrz;
    spawner.spawn(bit_send(tx, receiver, e_nrz)).unwrap();
    spawner.spawn(bit_receive_and_decode(rx, e_nrz)).unwrap();

    info!("starting loop");
    loop {
        msg_encode(b"ahoj", &sender).await;
        msg_encode(b"hello", &sender).await;

        let data = [0x01, 0x02, 0x03, 0x04];
        msg_encode(&data, &sender).await;

        info!("frame sent");
        embassy_time::Timer::after(Duration::from_secs(1)).await;
    }
}
