use crate::tui::ecs::commands::CommandQueue;
use crate::tui::ecs::components::*;
use crate::tui::ecs::events::EventBus;
use crate::tui::ecs::resources::*;

freecs::ecs! {
    World {
        position: Position => POSITION,
        velocity: Velocity => VELOCITY,
        sprite: Sprite => SPRITE,
        collider: Collider => COLLIDER,
        name: Name => NAME,
        visibility: Visibility => VISIBILITY,
        z_index: ZIndex => Z_INDEX,
        parent: Parent => PARENT,
        label: Label => LABEL,
        tilemap: Tilemap => TILEMAP,
        sprite_animation: SpriteAnimation => SPRITE_ANIMATION,
        local_offset: LocalOffset => LOCAL_OFFSET,
    }
    Resources {
        terminal_size: TerminalSize,
        keyboard: Keyboard,
        timing: Timing,
        camera: Camera,
        event_bus: EventBus,
        command_queue: CommandQueue,
        should_exit: bool,
        mouse: Mouse
    }
}

pub fn apply_commands(world: &mut World) {
    let commands = world.resources.command_queue.drain();
    for command in commands {
        match command {
            crate::tui::ecs::commands::WorldCommand::SpawnEntity { mask } => {
                world.spawn_entities(mask, 1);
            }
            crate::tui::ecs::commands::WorldCommand::DespawnEntity { entity } => {
                world.despawn_entities(&[entity]);
            }
            crate::tui::ecs::commands::WorldCommand::AddComponents { entity, mask } => {
                world.queue_add_components(entity, mask);
                world.apply_commands();
            }
            crate::tui::ecs::commands::WorldCommand::RemoveComponents { entity, mask } => {
                world.queue_remove_components(entity, mask);
                world.apply_commands();
            }
        }
    }
}
