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

const blocks = ['stone', 'metal','asphalt']

world.afterEvents.entityHitEntity.subscribe((event) => {
    const { damagingEntity, hitEntity } = event;
    
    if (
        damagingEntity.typeId == "minecraft:player" &&
        hitEntity.typeId.includes("carrinho")
    ) {
        let locationHitEntity = hitEntity.location
        try {
            const getItem = (source) => {
                /**
                 * @type {EntityEquippableComponent}
                 */
                const componet = damagingEntity.getComponent('minecraft:equippable');
                if (componet.getEquipment(EquipmentSlot.Mainhand) != undefined)
                    return componet.getEquipment(EquipmentSlot.Mainhand);
                else 
                    return new ItemStack('minecraft:stick',1)
            }
            if (getItem(damagingEntity).typeId ==
                "kt_cl:remove_vehicle"
            ) {
                damagingEntity.runCommand(
                    "playsound removetool.vehicle @a[r=4]"
                );
                const itemStack = new ItemStack(
                    hitEntity.typeId + "_spawn_egg",
                    1
                );
                hitEntity.remove();
                damagingEntity.dimension.spawnItem(
                    itemStack,
                    locationHitEntity
                );
            } else if (
                getItem(damagingEntity).typeId ==
                "kt_cl:colors"
            ) {
                damagingEntity.runCommand(
                    "playsound colortool.vehicle @a[r=4]"
                );
                switch (hitEntity.getComponent("minecraft:skin_id").value) {
                    case 0: {
                        hitEntity.triggerEvent("kt_ct:color_red");
                        break;
                    }
                    case 1: {
                        hitEntity.triggerEvent("kt_ct:color_blue");
                        break;
                    }
                    case 2: {
                        hitEntity.triggerEvent("kt_ct:color_yellow");
                        break;
                    }
                    case 3: {
                        hitEntity.triggerEvent("kt_ct:color_default");
                        break;
                    }
                }
            }
        } catch (e) {
            
        }
    }
});

world.afterEvents.itemUse.subscribe((event) => {
    const { itemStack, source } = event;
    if (itemStack.typeId == "ent_co:asphalt_driller") {
    }
});

function relativeLocation(entity, distance) {
    // Obtém a localização da entidade
    const entityLocation = entity.location;

    // Obtém a direção de visão da entidade
    const viewDirection = entity.getViewDirection();

    // Calcula as coordenadas dos blocos atrás da entidade
    const blocksBehindX = entityLocation.x + viewDirection.x * distance;
    const blocksBehindY = entityLocation.y;
    const blocksBehindZ = entityLocation.z + viewDirection.z * distance;

    const coor = { x: blocksBehindX, y: blocksBehindY, z: blocksBehindZ };
    // Retorna a localização dos blocos atrás da entidade
    return coor;
}

world.afterEvents.itemUse.subscribe((event) => {
    const {itemStack,source} = event;
    if (itemStack.typeId == 'ent_co:asphalt_driller') {
        const block = source.getBlockFromViewDirection({
            maxDistance: 5,
            includePassableBlocks: true,
        });
        if (block != undefined){
            const blockLocation = block.block.location
        blocks.forEach((blockTag) => {
            if (block.block.hasTag(blockTag)) {
                source.runCommand(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} air destroy`)
            }
        })
        }
        
    }
})

system.runInterval(() => {
    world.getAllPlayers().forEach((player) => {
        player.dimension
            .getEntities({
                location: player.location,
                maxDistance: 1.5,
                minDistance: 0,
                closest: 2
            })
            .forEach((victim) => {
                if (victim.typeId.includes("carrinho") && !player.isSneaking) {
                    let coor = relativeLocation(player, 1.5);
                    victim.teleport(coor);
                    victim.setRotation(player.getRotation());
                    victim.playAnimation('animation.kt_wheelbarrow.player_on')
                }
            });
    });
});

