// TODO:
// * Determine where local assets folder needs to be created
// * Create local assets folder
// * Recusrively laod that folder and watch for changes
// * Copy assets into local folder in leue of importing them
// * Check portability by moving binary + folder to new location

use std::time::Duration;

use bevy::{asset::ChangeWatcher, prelude::*};
use monologue_trees::{debug::*, ui};

fn main() {
    App::new()
        .add_plugins((
            DefaultPlugins
                .set(WindowPlugin {
                    primary_window: Some(Window {
                        title: "Serialization WTF".into(),
                        resolution: (640., 480.).into(),
                        ..default()
                    }),
                    ..default()
                })
                .set(AssetPlugin {
                    asset_folder: "assets".into(),
                    // Tell the asset server to watch for asset changes on disk:
                    watch_for_changes: ChangeWatcher::with_delay(Duration::from_millis(0)),
                    ..default()
                }),
            DebugInfoPlugin,
            ui::GameUiPlugin { ..default() },
        ))
        .register_type::<LevelRoot>()
        .register_type::<Other>()
        .register_type::<Choice>()
        .add_systems(Startup, init)
        .add_systems(Update, serialize_debug.run_if(pending))
        .run();
}

#[derive(Debug, Component, Default, Reflect)]
#[reflect(Component)]
struct LevelRoot;

#[derive(Debug, Component, Default, Reflect)]
#[reflect(Component)]
struct Other {
    inner: String,
}

#[derive(Debug, Component, Default, Reflect)]
#[reflect(Component)]
enum Choice {
    #[reflect(default)]
    #[default]
    One,
    Two,
    Three,
}

fn init(mut commands: Commands) {
    commands.spawn((
        SpatialBundle { ..default() },
        LevelRoot::default(),
        Name::new("Root Entity"),
        Other::default(),
        Choice::default(),
    ));
}

fn serialize_debug(query: Query<Entity, With<LevelRoot>>, world: &World) {
    let entities = query.iter().collect();
    print!("{}", ser(entities, world));
}

fn pending(query: Query<Entity, With<LevelRoot>>, mut done: Local<bool>) -> bool {
    if !*done {
        if query.iter().len() > 0 {
            *done = true;
        } else {
            *done = false;
        }
        return *done;
    }
    return false;
}

fn ser(entities: Vec<Entity>, world: &World) -> String {
    let app_type_registry = world.resource::<AppTypeRegistry>().clone();

    let scene = {
        let mut builder = DynamicSceneBuilder::from_world(world.clone());
        builder
            .allow_all_resources()
            .allow_all()
            .deny::<ComputedVisibility>()
            .extract_entities(entities.into_iter());
        builder.build()
    };

    scene
        .serialize_ron(&app_type_registry)
        .expect("Serialize scene")
}
