use crate::HDR_BYTES;
use crate::ecs::EditorWorld;
use nightshade::prelude::*;

pub fn switch_system(editor_world: &mut EditorWorld, world: &mut World) {
    let right_pressed = world
        .resources
        .input
        .keyboard
        .is_key_pressed(KeyCode::ArrowRight);
    let left_pressed = world
        .resources
        .input
        .keyboard
        .is_key_pressed(KeyCode::ArrowLeft);

    if right_pressed && !editor_world.resources.sun.right_arrow_was_pressed {
        world.resources.render_settings.atmosphere =
            world.resources.render_settings.atmosphere.next();
    }
    if left_pressed && !editor_world.resources.sun.left_arrow_was_pressed {
        world.resources.render_settings.atmosphere =
            world.resources.render_settings.atmosphere.previous();
    }

    editor_world.resources.sun.right_arrow_was_pressed = right_pressed;
    editor_world.resources.sun.left_arrow_was_pressed = left_pressed;

    let current_atmosphere = world.resources.render_settings.atmosphere;
    if current_atmosphere != editor_world.resources.sun.previous_atmosphere {
        if current_atmosphere == Atmosphere::DayNight {
            editor_world.resources.sun.day_night_hour = 12.0;
            editor_world.resources.sun.last_ibl_hour = 12.0;
            world.resources.renderer_state.day_night.hour = 12.0;
            capture_procedural_atmosphere_ibl(world, Atmosphere::DayNight, 12.0);
            capture_ibl_snapshots(
                world,
                Atmosphere::DayNight,
                vec![0.0, 4.0, 7.0, 10.0, 14.0, 17.0, 20.0],
            );
        } else if current_atmosphere.is_procedural() {
            capture_procedural_atmosphere_ibl(world, current_atmosphere, 0.0);
        } else if current_atmosphere == Atmosphere::Hdr {
            load_hdr_skybox(world, HDR_BYTES.to_vec());
        }
        editor_world.resources.sun.previous_atmosphere = current_atmosphere;
    }
}

pub fn tick_day_night(editor_world: &mut EditorWorld, world: &mut World) {
    if world.resources.render_settings.atmosphere != Atmosphere::DayNight {
        return;
    }
    if !editor_world.resources.sun.auto_cycle {
        return;
    }
    let delta = world.resources.window.timing.delta_time;
    let mut hour = editor_world.resources.sun.day_night_hour + delta * 0.5;
    if hour >= 24.0 {
        hour -= 24.0;
    }
    editor_world.resources.sun.day_night_hour = hour;

    let last = editor_world.resources.sun.last_ibl_hour;
    if (hour - last).abs() > 1.0 || hour < last {
        capture_procedural_atmosphere_ibl(world, Atmosphere::DayNight, hour);
        editor_world.resources.sun.last_ibl_hour = hour;
    }
    world.resources.renderer_state.day_night.hour = hour;
}
