#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_futures::select::Either;
use embassy_net::StackResources;
use embassy_stm32::eth::generic_smi::GenericSMI;
use embassy_stm32::eth::{Ethernet, PacketQueue};
use embassy_stm32::gpio::Pull;
use embassy_stm32::peripherals::ETH;
use embassy_stm32::time::Hertz;
use embassy_stm32::{bind_interrupts, eth, Config};
use embassy_time::Timer;
use static_cell::StaticCell;
use {defmt_rtt as _, panic_probe as _};

bind_interrupts!(struct Irqs {
    ETH => eth::InterruptHandler;
});

type Device = Ethernet<'static, ETH, GenericSMI>;

#[embassy_executor::task]
async fn net_task(mut runner: embassy_net::Runner<'static, Device>) -> ! {
    runner.run().await
}

#[embassy_executor::task]
async fn sync_task(
    mut hsync: embassy_stm32::exti::ExtiInput<'static>,
    mut vsync: embassy_stm32::exti::ExtiInput<'static>,
) -> ! {
    loop {
        let hlo = hsync.wait_for_falling_edge();
        let vlo = vsync.wait_for_falling_edge();
        let res = embassy_futures::select::select(hlo, vlo).await;
        if let Either::First(_) = res {
        }
    }
}

#[embassy_executor::main]
async fn main(spawner: Spawner) -> ! {
    let mut config = Config::default();
    {
        use embassy_stm32::rcc::*;
        config.rcc.hse = Some(Hse {
            freq: Hertz(8_000_000),
            mode: HseMode::Bypass,
        });
        config.rcc.pll_src = PllSource::HSE;
        config.rcc.pll = Some(Pll {
            prediv: PllPreDiv::DIV4,
            mul: PllMul::MUL216,
            divp: Some(PllPDiv::DIV2), // 8mhz / 4 * 216 / 2 = 216Mhz
            divq: None,
            divr: None,
        });
        config.rcc.ahb_pre = AHBPrescaler::DIV1;
        config.rcc.apb1_pre = APBPrescaler::DIV4;
        config.rcc.apb2_pre = APBPrescaler::DIV2;
        config.rcc.sys = Sysclk::PLL1_P;
    }
    let p = embassy_stm32::init(config);

    info!("Hello World!");

    let hsync = embassy_stm32::exti::ExtiInput::new(p.PC13, p.EXTI13, Pull::Up);
    let vsync = embassy_stm32::exti::ExtiInput::new(p.PC14, p.EXTI14, Pull::Up);
    unwrap!(spawner.spawn(sync_task(hsync, vsync)));

    // Generate random seed.
    let seed = 0xdeadbeefcafebabe;

    let mac_addr = [0x00, 0x00, 0xDE, 0xAD, 0xBE, 0xEF];

    static PACKETS: StaticCell<PacketQueue<4, 4>> = StaticCell::new();
    let device = Ethernet::new(
        PACKETS.init(PacketQueue::<4, 4>::new()),
        p.ETH,
        Irqs,
        p.PA1,
        p.PA2,
        p.PC1,
        p.PA7,
        p.PC4,
        p.PC5,
        p.PG13,
        p.PB13,
        p.PG11,
        GenericSMI::new(0),
        mac_addr,
    );

    let config = embassy_net::Config::dhcpv4(Default::default());

    // Init network stack
    static RESOURCES: StaticCell<StackResources<3>> = StaticCell::new();
    let (stack, runner) = embassy_net::new(device, config, RESOURCES.init(StackResources::new()), seed);

    // Launch network task
    unwrap!(spawner.spawn(net_task(runner)));

    // Ensure DHCP configuration is up before trying connect
    stack.wait_config_up().await;

    info!("Network task initialized");

    // Then we can use it!
    let mut rx_buffer = [0; 4096];
    let mut rx_meta = [embassy_net::udp::PacketMetadata::EMPTY; 16];
    let mut tx_buffer = [0; 4096];
    let mut tx_meta = [embassy_net::udp::PacketMetadata::EMPTY; 16];

    let mut socket = embassy_net::udp::UdpSocket::new(stack, &mut rx_meta, &mut rx_buffer, &mut tx_meta, &mut tx_buffer);

    let local = stack.config_v4().unwrap().address.address();
    let r = socket.bind(embassy_net::IpEndpoint{
        addr: embassy_net::IpAddress::Ipv4(local),
        port: 2137,
    });
    if let Err(e) = r {
        info!("could not bind socket: {:?}", e);
        loop {
            Timer::after_secs(1).await;
        }
    }

    loop {
        let meta = smoltcp::phy::PacketMeta::default();
        let to = embassy_net::udp::UdpMetadata {
            endpoint: embassy_net::IpEndpoint { addr: embassy_net::IpAddress::v4(255,255,255,255), port: 2137 },
            local_address: None,
            meta,
        };
        let r = socket.send_to(&[0xdeu8, 0xadu8, 0xbeu8, 0xefu8], to).await;
        if let Err(e) = r {
            info!("send error: {:?}", e);
            Timer::after_secs(5).await;
        } else {
            Timer::after_millis(100).await;
        }
    }
}
