import { system, world, ItemComponentTypes, EntityComponentTypes } from "@minecraft/server";
import { multiplyVector3Number } from "util/vector3Functions";
export const useAmethystStaff = (data) => {
    const itemStack = data.itemStack;
    const source = data.source;
    if (itemStack.typeId == "minere:amethyst_staff") {
        system.run(() => {
            if (!source.runCommand("clear @s[m=!c] amethyst_shard 0 1").successCount && source.getGameMode() !== "creative") {
                return;
            }
            const durability = itemStack.getComponent(ItemComponentTypes.Durability);
            const inventory = source.getComponent(EntityComponentTypes.Inventory);
            if (!durability || !inventory) {
                return;
            }
            world.playSound("step.amethyst_block", source.location);
            let loc = { x: source.location.x + source.getViewDirection().x * 1.5, y: source.location.y + 1.5 + source.getViewDirection().y * 1.5, z: source.location.z + source.getViewDirection().z * 1.5 };
            let fireball = source.dimension.spawnEntity("minere:amethyst_projectile", loc);
            const proj = fireball.getComponent(EntityComponentTypes.Projectile);
            proj.owner = source;
            fireball.setRotation({
                x: -1 * source.getRotation().x,
                y: -1 * source.getRotation().y,
            });
            fireball.applyImpulse(multiplyVector3Number(source.getViewDirection(), 2.25));
            if (source.getGameMode() === "creative") {
                return;
            }
            if (durability.damage == durability.maxDurability) {
                world.playSound("random.break", source.location);
                inventory.container.setItem(source.selectedSlotIndex, null);
            }
            else {
                const enchantments = itemStack.getComponent(ItemComponentTypes.Enchantable);
                if (enchantments) {
                    const unbreaking = enchantments.getEnchantment("unbreaking");
                    if (unbreaking) {
                        const rand = Math.floor(Math.random() * (unbreaking.level + 1));
                        if (rand !== 0) {
                            return;
                        }
                    }
                }
                durability.damage++;
                inventory.container.setItem(source.selectedSlotIndex, itemStack);
            }
        });
    }
};
