#![no_std]
#![no_main]

// TODO remove
#![allow(unused)]

extern crate panic_halt;

use core::fmt::Write;
use core::{
    arch::asm,
    ptr::{read_volatile, write_volatile},
};

use embedded_hal::prelude::{_embedded_hal_blocking_i2c_Read, _embedded_hal_blocking_i2c_Write};
use mcp4726::Status;
use riscv_rt::entry;
use smoltcp::wire::{IpAddress, Ipv4Address};
use smoltcp::{
    iface::{SocketSet, SocketStorage},
    time::Instant,
    wire::HardwareAddress,
};

mod eth;
mod i2c;
mod mcp4726;
mod uart;
mod logging;

const MAC: [u8; 6] = [0xA0, 0xBB, 0xCC, 0xDD, 0xEE, 0xF0];

// use `main` as the entry point of this application
// `main` is not allowed to return
#[entry]
fn main() -> ! {
    //unsafe { eth::init(); }

    //let blink_period = unsafe {
    //    if eth::is_wishbone_correct() {
    //        10_000_000
    //    } else {
    //        500_000
    //    }
    //};
    let blink_period = 10_000_000u32;
    let mut uart = uart::AmlibUart::new(0x0200_0040);

    let mut device = unsafe { eth::LiteEthDevice::try_init(0x0300_0000).unwrap() };

    use smoltcp::wire::{EthernetAddress, HardwareAddress};
    let mut config = smoltcp::iface::Config::default();
    config.hardware_addr = Some(HardwareAddress::Ethernet(EthernetAddress::from_bytes(&MAC)));

    let mut iface = smoltcp::iface::Interface::new(config, &mut device);
    // Set address
    iface.update_ip_addrs(|ip_addrs| {
        ip_addrs
            .push(smoltcp::wire::IpCidr::new(
                IpAddress::Ipv4(Ipv4Address::new(192, 168, 88, 69)),
                24,
            ))
            .unwrap();
    });

    iface
        .routes_mut()
        .add_default_ipv4_route(Ipv4Address::new(192, 168, 88, 1))
        .unwrap();

    // Create socket set with 4 available
    let mut socket_storage = [SocketStorage::EMPTY; 4];
    let mut socket_set = SocketSet::new(&mut socket_storage[..]);

    let mut last_blink: u32 = 0;
    let mut toggle = false;
    defmt::info!("Done setup");

    loop {
        let now = millis();
        if now - last_blink > 1000 {
            last_blink = now;
            toggle = !toggle;
            write_led(if toggle { 1 } else { 0 });
        }

        if iface.poll(Instant::from_millis(now), &mut device, &mut socket_set) {
            //writeln!(uart, "iface did something");
        }
    }
}

fn busy_wait(ms: u32) {
    let start = millis();
    while millis() - start < ms {
        unsafe {
            asm!("nop");
        }
    }
}

fn write_led(val: u32) {
    unsafe {
        write_reg(0x01200000, val);
    }
}

unsafe fn write_reg<T>(addr: u32, value: T) {
    write_volatile(addr as *mut T, value);
}

unsafe fn read_reg<T>(addr: u32) -> T {
    return read_volatile(addr as *mut T);
}

fn millis() -> u32 {
    unsafe { read_reg(0x01300000) }
}
