use bevy::{prelude::*, state::state::FreelyMutableState, window::WindowResized};

/// Deck and Cards
pub struct ViewPlugin;

impl Plugin for ViewPlugin {
    fn build(&self, app: &mut App) {
        app.init_state::<ViewState>()
            .add_systems(Update, update_window_info)
            .add_systems(Update, state_monitor);
    }
}

///
/// State component for which view an entity is associated with
///
#[derive(States, Component, Default, Clone, Eq, PartialEq, Hash, Debug)]
pub(crate) enum ViewState {
    #[default]
    None,
    Menu,
    Play,
    HowToPlay,
    About,
    Sets,
    Deck,
}

pub(crate) fn button_set_state<S: FreelyMutableState + Clone>(
    s: S,
) -> impl Fn(Trigger<Pointer<Click>>, ResMut<NextState<S>>) {
    move |_trigger: Trigger<Pointer<Click>>, mut next: ResMut<NextState<S>>| next.set(s.clone())
}

fn state_monitor(
    mut events: EventReader<StateTransitionEvent<ViewState>>,
    mut entities: Query<(&ViewState, &mut Visibility)>,
) {
    events.read().for_each(|event| {
        entities
            .iter_mut()
            .for_each(|(view_state, mut visibility)| {
                if Some(view_state) == event.entered.as_ref() {
                    *visibility = Visibility::Inherited;
                } else {
                    *visibility = Visibility::Hidden;
                }
            });
    });
}

fn update_window_info(mut events: EventReader<WindowResized>, mut _windows: Query<&mut Window>) {
    events
        .read()
        .for_each(|WindowResized { height, width, .. }| {
            info!("Window resized {} {}", height, width);

            let new_scale_factor = {
                let height_ratio = 800.0 / height;
                let width_ratio = 500.0 / width;
                height_ratio.min(width_ratio)
            };
            // let window = windows.single_mut();
            // window.resolution.set_scale_factor(new_scale_factor);

            info!("Proposed scale factor: {:?}", new_scale_factor);
        });
}
