use bevy::prelude::*;
use bevy_egui::EguiPrimaryContextPass;

pub struct DebugPlugin;

mod systems;

#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub struct DebugSet;

impl Plugin for DebugPlugin {
    fn build(&self, app: &mut App) {
        app.configure_sets(Last, DebugSet.run_if(is_debug_enabled));
        app.configure_sets(Update, DebugSet.run_if(is_debug_enabled));
        app.configure_sets(EguiPrimaryContextPass, DebugSet.run_if(is_debug_enabled));

        app.insert_resource(DebugMode::on())
            .add_plugins((
                // WorldInspector requires EguiPlugin plugin to be added before it
                bevy_egui::EguiPlugin::default(),
                bevy_inspector_egui::quick::WorldInspectorPlugin::new().run_if(is_debug_enabled),
            ))
            .add_systems(
                EguiPrimaryContextPass,
                systems::site_loader_ui.in_set(DebugSet),
            )
            .add_systems(Update, systems::space_to_load_random_site.in_set(DebugSet))
            .add_systems(Update, debug_toggle);
    }
}

#[derive(Reflect, Resource, Default)]
#[reflect(Resource)]
pub struct DebugMode {
    pub enabled: bool,
}

impl DebugMode {
    pub fn on() -> Self {
        Self { enabled: true }
    }

    pub fn off() -> Self {
        Self { enabled: false }
    }
}

pub fn is_debug_enabled(debug_mode: Res<DebugMode>) -> bool {
    debug_mode.enabled
}

fn debug_toggle(input: Res<ButtonInput<KeyCode>>, mut debug_mode: ResMut<DebugMode>) {
    if input.just_pressed(KeyCode::KeyP) {
        debug_mode.enabled = !debug_mode.enabled
    }
}
