use crate::println;
use crate::print;
use crate::vga_buffer::WRITER;
use lazy_static::lazy_static;
use crate::move_cursor_back;
use crate::simple_commands;
use simple_commands::simple_commands_help;
use simple_commands::simple_commands_lupus;

use pc_keyboard::{layouts, DecodedKey, HandleControl, Keyboard, ScancodeSet1};
use spin::Mutex;
use x86_64::instructions::port::Port;
use alloc::string::String;

pub fn keyboard_intertupt() {
    lazy_static! {
        static ref KEYBOARD: Mutex<Keyboard<layouts::Us104Key, ScancodeSet1>> =
            Mutex::new(Keyboard::new(layouts::Us104Key, ScancodeSet1,
                HandleControl::Ignore)
            );
    }
    static mut WHOLE_STRING: String = String::new();
    let mut keyboard = KEYBOARD.lock();
    let mut port = Port::new(0x60);

    let scancode: u8 = unsafe { port.read() };
    if let Ok(Some(key_event)) = keyboard.add_byte(scancode) {
        if let Some(key) = keyboard.process_keyevent(key_event) {
            match key {
                DecodedKey::Unicode(character) => {
                    unsafe {
                        // Handle Backspace (ASCII 0x08)
                        match character{
                            '\x08' => {move_cursor_back!(); WHOLE_STRING.pop();},
                            '\n' => {print!("{}", character); check_command_list(WHOLE_STRING.as_str()); WHOLE_STRING.clear();},
                            _ => {print!("{}", character); WHOLE_STRING.push(character);}, // Füge das Zeichen zum Puffer hinzu
                        }
                    }
                }
                DecodedKey::RawKey(key) => print!("{:?}", key),
            }
        }
    }
}

fn check_command_list(command: &str) {
    match command{
        "help" => simple_commands_help(),
        "lupus" => simple_commands_lupus(),
        _ => print!("Invalid Input"),
    }
}