import * as Vector3 from "../vector3";
import * as utils from "../utils";
import { system, world, EquipmentSlot } from "@minecraft/server";

export async function onItemUse(event) {
    const player = event.source;
    const item = event.itemStack;
    if (item && item.typeId === "pu_sg:lightning_sword") {
        const blockHit = player.getBlockFromViewDirection({ maxDistance: 100 });
        if (blockHit && blockHit.block.isValid()) {
            
            player.dimension.spawnEntity("minecraft:lightning_bolt", blockHit.block.location);

            if (item.getComponent("minecraft:durability").damage < (item.getComponent("minecraft:durability").maxDurability - 1)) {
                const newItem = await item.clone();
                newItem.getComponent("minecraft:durability").damage = item.getComponent("minecraft:durability").damage + 1;
                await player.getComponent("inventory").container.setItem(player.selectedSlotIndex, newItem);
            } else {
                player.playSound('random.break');
                await player.getComponent("inventory").container.setItem(player.selectedSlotIndex, null);
            }
        }
    }
}

export async function onEntityHurt(event) {
    const source = event.damageSource.damagingEntity;
    const entity = event.hurtEntity;
    if (source?.typeId === "minecraft:player") {
        const equippable = source.getComponent('equippable');
        if (!equippable) return;
        const mainhand = equippable.getEquipment(EquipmentSlot.Mainhand);
        if (mainhand?.typeId === 'pu_sg:lightning_sword') {
            if(entity.isValid()){
                const dimension = entity.dimension;
                dimension.spawnParticle("pu_sg:lightning_sword_1", {x: entity.location.x, y: entity.location.y + 1, z: entity.location.z});
                dimension.spawnParticle("pu_sg:lightning_sword_2", {x: entity.location.x, y: entity.location.y + 1, z: entity.location.z});
                dimension.playSound("pu_sg:lightning_sword_attack", entity.location);
            }
        }
    }
}