use bevy::prelude::*;

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

pub fn setup_persistent_camera(mut commands: Commands) {
    commands.spawn((
        Name::from("Persistent camera"),
        Transform::from_xyz(0., 301.8, 9.),
        GameCamera,
    ));
}

pub fn load_random_site(mut on_site_load: EventWriter<OnSiteLoad>, game_world: Res<GameWorld>) {
    on_site_load.write(OnSiteLoad {
        site: fastrand::choice(game_world.sites.values())
            .expect("Picking random site")
            .id(),
    });
}

pub fn create_site_scene(
    mut site_loaded_event: EventReader<OnSiteLoad>,
    mut commands: Commands,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut meshes: ResMut<Assets<Mesh>>,
    asset_server: Res<AssetServer>,
    destroy_query: Query<Entity, With<DestroyOnSceneChange>>,
    game_world: Res<GameWorld>,
) {
    for site_loaded in site_loaded_event.read() {
        info!("Loading {}", site_loaded.site);
        let site = game_world
            .sites
            .get(&site_loaded.site)
            .expect("Finding site by id");

        // Destroy old scenes
        for entity in destroy_query.iter() {
            match commands.get_entity(entity) {
                Ok(mut entity) => entity.despawn(),
                Err(err) => warn!("{err}"),
            }
        }

        let scene_path = GltfAssetLabel::Scene(0).from_asset("scenes/site-area.glb");

        asset_server.reload(&scene_path);

        commands.spawn((
            Name::from("Site"),
            SiteScene(site_loaded.site),
            DestroyOnSceneChange,
            Transform::from_xyz(0., 300.0, 0.),
            Visibility::default(),
            SceneRoot(asset_server.load(&scene_path)),
        ));
    }
}
