mod consts;
mod gameover;
mod gameplay;
mod load;
mod pause;
mod resources;
mod title;

use bevy::prelude::*;
use consts::RESOLUTION;
use gameover::GameOverPlugin;
use gameplay::GameplayPlugin;
use pause::PausePlugin;
use resources::Modifiers;
use crate::load::LoadPlugin;
use crate::title::TitlePlugin;

use crate::resources::AppState;

pub mod prelude {
    pub mod consts {
        pub use crate::consts::*;
    }
    pub use super::NonogramApp;
}

#[derive(Clone, Copy, Debug)]
pub struct NonogramApp;

impl Plugin for NonogramApp {

    fn build(&self, app: &mut App) {
        app
            .init_state::<AppState>()
            .add_plugins(LoadPlugin)
            .add_plugins(TitlePlugin)
            .add_plugins(GameplayPlugin)
            .add_plugins(PausePlugin)
            .add_plugins(GameOverPlugin)
            .add_systems(PreUpdate, resize_system)
            .add_systems(Update, exit_system)
        ;
    }
}

fn exit_system(
    input: Res<ButtonInput<KeyCode>>,
    mut modifiers: ResMut<Modifiers>,
    mut exit: EventWriter<AppExit>,
) {
    #[cfg(target_os="macos")]
    let ctrl = input.pressed(KeyCode::SuperLeft);
    #[cfg(not(target_os="macos"))]
    let ctrl = input.pressed(KeyCode::ControlLeft) || input.pressed(KeyCode::ControlRight);
    if ctrl && input.just_pressed(KeyCode::KeyQ) {
        exit.write(AppExit::Success);
    }
    modifiers.ctrl = ctrl;
    modifiers.shift = input.pressed(KeyCode::ShiftLeft) || input.pressed(KeyCode::ShiftRight);
}

fn resize_system(mut window_query: Query<&mut Window, Changed<Window>>) {
    if let Ok(mut window) = window_query.single_mut() {
        let resolution = &mut window.resolution;
        let xf = resolution.physical_width() as f32 / RESOLUTION.x;
        let yf = resolution.physical_height() as f32 / RESOLUTION.y;
        let factor = xf.min(yf);
        resolution.set_scale_factor_override(Some(factor));
    }
}
