use nalgebra_glm::Vec2;
use winit::keyboard::KeyCode;

use crate::ecs::world::World;

use crate::prelude::*;
pub fn ui_retained_input_sync_system(world: &mut World) {
    if !world.resources.retained_ui.enabled {
        return;
    }

    world.resources.retained_ui.frame.events.clear();
    world
        .resources
        .retained_ui
        .accessibility
        .announce_queue
        .clear();
    world.resources.retained_ui.timing.delta_time = world.resources.window.timing.delta_time;
    world.resources.retained_ui.timing.current_time =
        world.resources.window.timing.uptime_milliseconds as f64 / 1000.0;

    let ctrl_held = world
        .resources
        .input
        .keyboard
        .is_key_pressed(KeyCode::ControlLeft)
        || world
            .resources
            .input
            .keyboard
            .is_key_pressed(KeyCode::ControlRight);
    let shift_held = world
        .resources
        .input
        .keyboard
        .is_key_pressed(KeyCode::ShiftLeft)
        || world
            .resources
            .input
            .keyboard
            .is_key_pressed(KeyCode::ShiftRight);

    world.resources.retained_ui.input.frame_chars = filter_chars(
        world.resources.input.keyboard.frame_chars.clone(),
        ctrl_held,
    );
    world.resources.retained_ui.input.frame_keys =
        world.resources.input.keyboard.frame_keys.clone();
    world.resources.retained_ui.input.scroll_delta = world.resources.input.mouse.wheel_delta;
    world.resources.retained_ui.input.ctrl_held = ctrl_held;
    world.resources.retained_ui.input.shift_held = shift_held;

    let mouse_state = world.resources.input.mouse.state;
    let mouse_drives_layout = mouse_state.intersects(
        crate::ecs::input::resources::MouseState::LEFT_CLICKED
            | crate::ecs::input::resources::MouseState::LEFT_JUST_PRESSED
            | crate::ecs::input::resources::MouseState::LEFT_JUST_RELEASED
            | crate::ecs::input::resources::MouseState::RIGHT_JUST_PRESSED
            | crate::ecs::input::resources::MouseState::RIGHT_JUST_RELEASED,
    );
    if mouse_drives_layout
        || world.resources.retained_ui.input.scroll_delta != Vec2::zeros()
        || !world.resources.retained_ui.input.frame_chars.is_empty()
        || !world.resources.retained_ui.input.frame_keys.is_empty()
    {
        ui_mark_layout_dirty(world);
    }
}

fn filter_chars(chars: Vec<char>, ctrl_held: bool) -> Vec<char> {
    if !ctrl_held {
        return chars;
    }
    chars.into_iter().filter(|c| !c.is_ascii()).collect()
}
