use crate::sim::prelude as sim;
use crate::{debug, game_setup, util};
use bevy::prelude::*;

pub mod prefab;
pub mod scene;
pub mod site;
pub mod systems;

pub fn init(app: &mut App) {
    let app = app.add_plugins((
        game_setup::GameSetupPlugin,
        util::UtilPlugin,
        debug::DebugPlugin,
    ));

    let definitions = sim::Definitions::from_default_directory().unwrap();
    let game_world = sim::GameWorld::generate_random(&definitions);
    // let game_world = match std::fs::read(sim::SAVE_FILE) {
    //     Ok(data) => {
    //         info!("Reading world data from \"{}\"", sim::SAVE_FILE);
    //         bincode::deserialize(&data).expect("Loading world data from file")
    //     }
    //     Err(_) => {
    //         info!("Generating mock world...");
    //         let world = sim::GameWorld::generate_mock(&definitions);
    //         info!("Writing new world data to \"{}\"", sim::SAVE_FILE);
    //         std::fs::write(sim::SAVE_FILE, bincode::serialize(&world).unwrap()).unwrap();
    //         world
    //     }
    // };

    app.register_type::<sim::Definitions>()
        .register_type::<sim::GameWorld>()
        .register_type::<scene::DestroyOnSceneChange>()
        .register_type::<site::SiteScene>()
        .register_type::<site::SiteEntrance>()
        .register_type::<prefab::GameCamera>()
        .add_event::<site::OnSiteLoad>()
        .insert_resource(definitions)
        .insert_resource(game_world)
        // Since Egui is currently configured to automatically insert PrimaryEguiContext to the
        // first created camera, we spawn a single camera and never delete it.
        .add_systems(
            Startup,
            (systems::setup_persistent_camera, systems::load_random_site),
        )
        .add_systems(Update, (systems::demo_3d, systems::advance_time))
        .add_systems(PostUpdate, systems::create_site_scene);

    app.add_plugins(bevy_skein::SkeinPlugin::default());
}
