#![no_std]
#![no_main]

use embassy_sync::mutex::Mutex;
use embassy_executor::Spawner;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_time::{Duration, Timer};
use esp_backtrace as _;
use esp_hal::{clock::CpuClock, gpio::{Input, Level, Output, Pull, AnyPin}};
use log::info;

type ButtonType =  Mutex<CriticalSectionRawMutex, Option<Input<'static>>>;
static BUTTON: ButtonType = Mutex::new(None);

#[embassy_executor::task]
async fn button_task(button: &'static ButtonType) {
    loop {
        let mut button_unlocked = button.lock().await;
        info!("pressed");


        if let Some(button_ref) = button_unlocked.as_mut(){
            button_ref.wait_for_rising_edge().await;
            info!("pressed");
        }
    }
}

#[esp_hal_embassy::main]
async fn main(spawner: Spawner) {
    let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
    let peripherals = esp_hal::init(config);
    esp_println::logger::init_logger_from_env();
    let timer0 = esp_hal::timer::systimer::SystemTimer::new(peripherals.SYSTIMER);
    esp_hal_embassy::init(timer0.alarm0);

    let button = Input::new(peripherals.GPIO3, Pull::Up);

    {
        let mut button_lock = BUTTON.lock().await;
        *button_lock = Some(button);
    }

    spawner.spawn(button_task(&BUTTON)).unwrap();

    let mut leds: [Output; 10] = [
        Output::new(peripherals.GPIO9, Level::Low),
        Output::new(peripherals.GPIO8, Level::Low),
        Output::new(peripherals.GPIO7, Level::Low),
        Output::new(peripherals.GPIO6, Level::Low),
        Output::new(peripherals.GPIO5, Level::Low),
        Output::new(peripherals.GPIO4, Level::Low),
        Output::new(peripherals.GPIO2, Level::Low),
        Output::new(peripherals.GPIO1, Level::Low),
        Output::new(peripherals.GPIO0, Level::Low),
        Output::new(peripherals.GPIO18, Level::Low),
    ];

    loop {

    }
}