//! The Judas kernel for raspberry pi.
//!
//! This is a kernel written in rust for raspberry pi 3 and 4.
//! This project is heavily inspired by https://github.com/rust-embedded/rust-raspberrypi-OS-tutorials,
//! but it's a project for discovering rust on embedded, so its architecture is less generic and
//! I'm trying to reuse knowledge from Telecom-Paris SE203 class as much as I can.

#![no_main]
#![no_std]
#![feature(format_args_nl)]
#![feature(panic_info_message)]

#![allow(dead_code)]

mod traits;
mod bsp;
mod utils;

mod panic;
mod print;

use core::arch::global_asm;
use core::arch::asm;

// TODO: handle this with features
//use crate::bsp::qemu::console::console;
use crate::bsp::rpi3::uart::console;
use crate::bsp::rpi3::gpio;

// TODO: move this to BSP
/// Pause the core with a infinit loop
#[inline(always)]
pub fn wait_forever() -> ! {
    loop {
        unsafe { asm!("wfe"); }
    }
}

// TODO: move this to BSP
global_asm!(include_str!("boot.s"));

/// Start the rust part of the kernel
#[no_mangle]
pub unsafe fn _start_rust() -> ! {

    // Set TX and RX function for pin 14 and 15
    match gpio::set_pin_fonction(14, gpio::PinFunction::AltFunc0) {
        _ => (),
    }
    match gpio::set_pin_fonction(15, gpio::PinFunction::AltFunc0) {
        _ => (),
    }
    // Debut led
    match gpio::set_pin_fonction(20, gpio::PinFunction::Output) {
        _ => (),
    }
    match gpio::set_pin_output_state(20, gpio::PinOutputState::Low) {
        _ => (),
    }
    bsp::rpi3::uart::init();
    println!("Hello there");

    match gpio::set_pin_fonction(21, gpio::PinFunction::Output) {
        Ok(()) => println!("Successfully set pin to output"),
        Err(err) => println!("Failled to set pin: {err}"),
    }
    loop {
        match gpio::set_pin_output_state(21, gpio::PinOutputState::High) {
            Ok(()) => (),
            Err(_err) => println!("Failled to set pin 21 to High"),
        }
        for _ in 0..5000000 {
            asm!("nop");
        }
        match gpio::set_pin_output_state(21, gpio::PinOutputState::Low) {
            Ok(()) => (),
            Err(_err) => println!("Failled to set pin 21 to Low"),
        }
        for _ in 0..5000000 {
            asm!("nop");
        }
    }
    /*
    println!("Hello there");
    panic!("Paniccccccc")
    */
}
