#![no_std]
#![no_main]

mod adc;
mod bus;
mod button;
mod display;
mod hardware;
mod led_state;
mod midi;

use cortex_m_rt::entry;
use panic_halt as _;

use defmt_rtt as _;

use button::ButtonHandler;
use midi::MidiProcessor;
use hardware::Hardware;
use display::DisplayController;
use embedded_midi::MidiMessage;
use midi_types::{Control, Channel, Value7};

defmt::timestamp!("{=u32}", {
    static mut COUNTER: u32 = 0;
    unsafe {
        COUNTER = COUNTER.wrapping_add(1);
        COUNTER
    }
});

#[entry]
fn main() -> ! {
    let mut hardware = Hardware::init();

    #[cfg(not(debug_assertions))]
    DisplayController::run_boot_sequence(&mut hardware.bus, &mut hardware.delay);

    let mut button_handler = ButtonHandler::new();
    let mut led_state = led_state::LedState::default();
    
    loop {
        for _ in 0..20 {
            for i in 0_u8..6_u8 {
                DisplayController::display_led_state(i, &mut hardware.bus, &led_state, &mut hardware.delay);
                hardware.bus.output(11, 4_u8 << i);

                button_handler.process_buttons(
                    &hardware.button_1_5,
                    &hardware.button_6_10,
                    &mut hardware.midi_tx,
                    i,
                );
            }
            
            MidiProcessor::process_message(&mut hardware.midi_rx, &mut led_state);
        }
        let (pedal_a_change, pedal_b_change) = hardware.adc.update_and_get_midi_changes();

        if let Some(value) = pedal_a_change {
            let msg = MidiMessage::ControlChange(Channel::C1, Control::from(1), Value7::from(value));
            hardware.midi_tx.write(&msg).ok();
        }

        if let Some(value) = pedal_b_change {
            let msg = MidiMessage::ControlChange(Channel::C1, Control::from(7), Value7::from(value));
            hardware.midi_tx.write(&msg).ok();
        }
    }
}

