use bevy_ecs::prelude::*;
use egor::{app::*, render::*};
use log::*;

use starbloom_base::prelude::*;
use starbloom_camera::*;
use starbloom_map::*;
use starbloom_tiles::*;
use starbloom_worldgen::*;

use crate::player::*;
struct MainPlugin();

impl Plugin for MainPlugin {
    fn create(world: &mut World, _schedule: &mut Schedule) {
        let mut regestry = world
            .get_resource_mut::<TileRegestry>()
            .expect(&"Could not get tile regestry");
        regestry.regester("starbloom:air", Tile::declare(false));
        regestry.regester("starbloom:debug", Tile::declare(true));

        world.spawn(Player {
            name: "guest".to_owned(),
        });
    }
}

#[cfg(not(target_arch = "wasm32"))]
egor::main!(main);
pub fn main() {
    #[cfg(target_arch = "wasm32")]
    wasm_logger::init(wasm_logger::Config::default().module_prefix("starbloom"));
    #[cfg(not(target_arch = "wasm32"))]
    env_logger::builder().format_timestamp(None).filter(Some("starbloom"), LevelFilter::Info).init();

    info!("STARBLOOM v{}", VERSION);

    let mut world: World = World::new();
    let mut schedule: Schedule = Schedule::default();

    CameraPlugin::create(&mut world, &mut schedule);
    MapPlugin::create(&mut world, &mut schedule);
    WorldgenPlugin::create(&mut world, &mut schedule);
    PlayerPlugin::create(&mut world, &mut schedule);
    MainPlugin::create(&mut world, &mut schedule);

    world.insert_non_send(GfxCmds::new());
    world.insert_resource(InputCtx::default());

    //wgpu::Limits::downlevel_webgl2_defaults();

    App::new()
        .title("STARBLOOM")
        .run(move |ctx: &mut FrameContext<'_>| {
            world
                .get_resource_mut::<InputCtx>()
                .unwrap()
                .update(ctx.input);

            ctx.gfx.clear(Color::BLUE);
            schedule.run(&mut world);

            world
                .get_non_send_mut::<GfxCmds>()
                .unwrap()
                .apply(&mut ctx.gfx);

            egui::Window::new("Debug").show(ctx.egui_ctx, |ui| {
                ui.label("this is a test");
            });

            #[cfg(feature = "show_fps")]
            ctx.gfx.text(&format!("FPS: {}", ctx.timer.fps));
        });
}