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

system.beforeEvents.startup.subscribe((initEvent) => {
    initEvent.blockComponentRegistry.registerCustomComponent("rustic:spawn_ride", {
        onPlayerInteract: e => {
            const { player, block, dimension } = e;
            const blockCenter = block.center();

            const chairEntity = dimension.spawnEntity("rustic:chair_entity",{ x: blockCenter.x, y: blockCenter.y - 0.2, z: blockCenter.z })

            const faceLocation = block.permutation.getState("minecraft:cardinal_direction");

            switch(faceLocation){
                case 'south':
                    chairEntity.runCommand(`tp ~ ~ ~ facing ~ ~ ~10`)
                    break;
                case 'north':
                    chairEntity.runCommand(`tp ~ ~ ~ facing ~ ~ ~-10`)
                    break;
                case 'west':
                    chairEntity.runCommand(`tp ~ ~ ~ facing ~-10 ~ ~`)
                    break;
                case 'east':
                    chairEntity.runCommand(`tp ~ ~ ~ facing ~10 ~ ~`)
                    break;
            }
            
            player.runCommand(`ride @s start_riding @e[type=rustic:chair_entity,c=1,x=${chairEntity.location.x},y=${chairEntity.location.y},z=${chairEntity.location.z}] teleport_rider`)
            
        },
        onPlayerBreak: e => {
            const dimension = e.dimension;
            const block = e.block;

            const entities = dimension.getEntitiesAtBlockLocation(block.center())

            for (const entity of entities){
                if (entity.typeId == "rustic:chair_entity"){
                    entity.triggerEvent("despawn")
                }
            }
        }
    });
});

export function randomTag() {
  return (Math.floor(10000 + Math.random() * 90000)).toString();
}