import { EntityTypeFamilyComponent, ItemStack, system, world } from "@minecraft/server";

let loop = (amount, callback) => {
    for(let i = 0; i < amount; i++) callback();
}

const spawner = {
    "pixell_bbo:craterus_spawner": (location, dimension) => {
        loop(5, () => dimension.spawnEntity("pixell_bbo:aphemus", location))
    },
    "pixell_bbo:ares_spawner": (location, dimension) => {
        loop(5, ()=> dimension.spawnEntity("pixell_bbo:caesar", location))
    },
    "pixell_bbo:hades_spawner": (location, dimension) => {
        loop(5, ()=> dimension.spawnEntity("pixell_bbo:madir", location))
    },
    "pixell_bbo:burazazu_spawner": (location, dimension) => {
        loop(5, ()=> dimension.spawnEntity("pixell_bbo:shinobi", location))
    },
    "pixell_bbo:sweet_spawner": (location, dimension) => {
        loop(2, ()=> dimension.spawnEntity("pixell_bbo:amenadiel", location))
    },
    "pixell_bbo:unknown_spawner": (location, dimension) => {
        loop(5, ()=> dimension.spawnEntity("pixell_bbo:stormi", location))
    }
}

world.beforeEvents.entityRemove.subscribe(e => {
    if(e.removedEntity.hasComponent(EntityTypeFamilyComponent.componentId)) {
        if(e.removedEntity.getComponent(EntityTypeFamilyComponent.componentId).hasTypeFamily("pixell_bbo:mobs")) {
            const dimension = e.removedEntity.dimension;

            const location = e.removedEntity.location;

            system.run(()=>{
                dimension.spawnItem(new ItemStack("pixell_bbo:souls", 1), location);
            })
        }
    }
})

world.beforeEvents.worldInitialize.subscribe(e => {
    e.blockComponentRegistry.registerCustomComponent("pixell_bbo:spawner", {
        onTick: ({block}) => {
            if(block.typeId in spawner) {
                spawner[block.typeId](block.center(), block.dimension);
            } else {
                return;
                //console.log("Spawner", "Not found: ", block.typeId);
            }

            system.run(()=>{
                block.setType("minecraft:air");
            })
        }
    })
})