use nightshade::prelude::*;
use nightshade::shell::{ShellState, shell_retained_ui};

#[derive(Default)]
pub struct EditorShellContext;

pub fn new_shell() -> ShellState<EditorShellContext> {
    let mut shell = ShellState::new(EditorShellContext);
    shell.register_builtin_commands();
    shell
}

pub fn run(shell: &mut ShellState<EditorShellContext>, world: &mut World) {
    if shell.visible {
        let alt_held = world
            .resources
            .input
            .keyboard
            .is_key_pressed(KeyCode::AltLeft)
            || world
                .resources
                .input
                .keyboard
                .is_key_pressed(KeyCode::AltRight);
        if !alt_held {
            for character in world.resources.input.keyboard.frame_chars.clone() {
                if !character.is_control() {
                    shell.input_buffer.push(character);
                }
            }
        }
    }
    let delta_time = world.resources.window.timing.delta_time;
    shell.update_animation(delta_time);
    shell_retained_ui(shell, world);
}

pub fn handle_key(
    shell: &mut ShellState<EditorShellContext>,
    world: &mut World,
    key_code: KeyCode,
    key_state: ElementState,
) {
    let pressed = key_state == ElementState::Pressed;
    if pressed {
        let alt_pressed = world
            .resources
            .input
            .keyboard
            .is_key_pressed(KeyCode::AltLeft)
            || world
                .resources
                .input
                .keyboard
                .is_key_pressed(KeyCode::AltRight);
        if key_code == KeyCode::KeyC && alt_pressed {
            shell.toggle();
            return;
        }
    }
    if shell.visible {
        shell.handle_key(key_code, pressed);
    }
}

pub fn is_capturing_input(shell: &ShellState<EditorShellContext>) -> bool {
    shell.visible || shell.dragging_resize || shell.dragging_scrollbar
}
