use bevy::prelude::*;
use bevy_egui::{EguiContexts, egui};

use crate::{game::site::OnSiteLoad, sim::prelude::*};

pub fn space_to_load_random_site(
    input: Res<ButtonInput<KeyCode>>,
    game_world: Res<GameWorld>,
    mut on_site_load: EventWriter<OnSiteLoad>,
) {
    if !input.just_pressed(KeyCode::Space) {
        return;
    }
    on_site_load.write(OnSiteLoad {
        site: fastrand::choice(game_world.sites.values())
            .expect("Picking random site")
            .id(),
    });
}

pub fn site_loader_ui(
    mut contexts: EguiContexts,
    game_world: ResMut<GameWorld>,
    mut on_site_load: EventWriter<OnSiteLoad>,
) -> Result {
    egui::Window::new("Site loader").show(contexts.ctx_mut()?, |ui| {
        ui.vertical(|ui| {
            ui.horizontal_wrapped(|ui| ui.label("Site filter (todo)"));
            ui.separator();
            egui::ScrollArea::vertical().show(ui, |ui| {
                ui.set_width(ui.available_width());
                let mut sites: Vec<&Site> = game_world.sites.values().collect();
                sites.sort_unstable_by(|a, b| {
                    if a.definition.id != b.definition.id {
                        a.definition.id.cmp(&b.definition.id)
                    } else {
                        a.id().cmp(&b.id())
                    }
                });
                for site in sites {
                    egui::CollapsingHeader::new(&site.name)
                        .id_salt(site.id())
                        .show(ui, |ui| {
                            if ui.button("load").clicked() {
                                on_site_load.write(OnSiteLoad { site: site.id() });
                            }
                            ui.collapsing(
                                format!("population: {}", site.creatures().len()),
                                |ui| {
                                    for creature in site.creatures().iter() {
                                        ui.label(creature.to_string());
                                    }
                                },
                            );
                        });
                }
            });
        });
    });
    Ok(())
}
