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

export function shootProjectile(player, projectileId, options) {
    const location = player.location;
    const direction = player.getViewDirection();
    const rotation = player.getRotation();
    const { power, sound, uncertainty } = options;

    const projectile = player.dimension.spawnEntity(projectileId, {
        x: location.x + direction.x * 0.5,
        y: location.y + 1.6,
        z: location.z + direction.z * 0.5,
    });
    projectile.setRotation({ x: rotation.x, y: rotation.y });

    const shootable = projectile.getComponent("minecraft:projectile");
    const velocity = {
        x: direction.x * power,
        y: direction.y * power,
        z: direction.z * power,
    };

    if (shootable) {
        shootable.owner = player;
        shootable.gravity = 0.0;

        player.playSound(sound, location);
        //shootable.shoot(velocity, { uncertainty });
        // projectile.clearVelocity();
        projectile.setDynamicProperty("speed", {
            x: direction.x * power,
            y: direction.y * power,
            z: direction.z * power,
        });

        projectile.applyImpulse({
            x: direction.x * power,
            y: direction.y * power,
            z: direction.z * power,
        });
    }
}

export function handleItemDurability(player, itemStack) {
    const equipment = player.getComponent("minecraft:equippable");

    const durability = itemStack.getComponent("minecraft:durability");

    const currentDurability = durability.damage;

    const maxDurability = durability.maxDurability;

    const newItem = itemStack.clone();

    if (currentDurability < maxDurability) {
        newItem.getComponent("minecraft:durability").damage = Math.min(
            maxDurability,
            currentDurability + 1
        );

        equipment.setEquipment(EquipmentSlot.Mainhand, newItem);
    } else {
        player.playSound("random.break");
        equipment.setEquipment(EquipmentSlot.Mainhand);
    }
}

system.runInterval(() => {
    const players = world.getAllPlayers();

    for (let player of players) {
        const projectiles = player.dimension.getEntities({
            families: ["projectile"],
        });

        for (let projectile of projectiles) {
            projectile.clearVelocity();
            const speed = projectile.getDynamicProperty("speed");
            if (speed) {
                projectile.applyImpulse(speed);
            }
        }
    }
});

export function getRandomBetween(min, max) {
    if (min > max) {
        const tempMin = Math.min(min, max);
        const tempMax = Math.max(min, max);

        return Math.round(Math.random() * (tempMax - tempMin) + tempMin);
    }
    return Math.round(Math.random() * (max - min) + min);
}
