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

export async function onItemUse(event) {
    const player = event.source;
    const item = event.itemStack;
    if (item && item.typeId === "pu_sg:necromancer_wand") {
        if (!player.getDynamicProperty("pu_sg_necromancer_wand")) {
            player.setDynamicProperty("pu_sg_necromancer_wand", true);
            
            const direction = Vector3.fromRotation(player.getRotation());
            
            let playerLocation = new Vector3.Vector3(player.location);
            let projectileSpawn = playerLocation.add(Vector3.Up.multiply(1.5)).add(direction.multiply(2));

            utils.runPlayerCommand(player, "playsound pu_sg:necromancer_wand_shoot @a[r=7] ~ ~ ~");   
        
            const projectile =  player.dimension.spawnEntity("pu_sg:necromancer_projectile", {x:projectileSpawn.x, y:projectileSpawn.y, z:projectileSpawn.z});
            const projectileVelocity = direction.multiply(3.5);
            projectile.applyImpulse({x: projectileVelocity.x, y:projectileVelocity.y, z: projectileVelocity.z});

            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);
            }

            system.runInterval(() => {
                player.setDynamicProperty("pu_sg_necromancer_wand", false);
            }, 30);
        }
    }
}