use crate::prelude::*;

pub(crate) struct LoadingPlugin;

impl Plugin for LoadingPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, initialize)
            .add_systems(Update, loading.run_if(in_state(GameState::Loading)))
            .add_systems(OnEnter(GameState::Loading), activate::<Loading>)
            .add_systems(OnExit(GameState::Loading), deactivate::<Loading>);
    }
}

#[derive(Debug, Component)]
struct Loading;

fn initialize(mut commands: Commands) {
    commands
        .spawn((
            Loading,
            NodeBundle {
                style: Style {
                    width: Val::Percent(100.0),
                    height: Val::Percent(100.0),
                    justify_content: JustifyContent::Center,
                    align_items: AlignItems::Center,
                    position_type: PositionType::Absolute,
                    ..default()
                },
                visibility: Visibility::Hidden,
                ..default()
            },
        ))
        .with_children(|parent| {
            parent.spawn((TextBundle {
                text: Text {
                    alignment: TextAlignment::Center,
                    sections: vec![TextSection {
                        value: "l o a d i n g . . .".into(),
                        style: TextStyle {
                            color: Color::WHITE.into(),
                            ..default()
                        },
                    }],
                    ..default()
                },
                background_color: Color::BLACK.with_a(0.5).into(),
                ..default()
            },));
        });
}

fn loading(
    server: Res<AssetServer>,
    sprites: Res<Assets<Image>>,
    gltfs: Res<Assets<Gltf>>,
    tweaks: Res<Assets<tweak::Tweaks>>,
    mut next_state: ResMut<NextState<GameState>>,
) {
    let s = (!sprites.is_empty())
        && sprites
            .ids()
            .all(|id| server.is_loaded_with_dependencies(id));
    let g = (!gltfs.is_empty()) && gltfs.ids().all(|id| server.is_loaded_with_dependencies(id));
    let t = (!tweaks.is_empty())
        && tweaks
            .ids()
            .all(|id| server.is_loaded_with_dependencies(id));

    debug!("s {} g {} t {}", s, g, t);

    if t {
        // s && g && t {
        next_state.set(GameState::Menu)
    }
}
