import { EntityComponentTypes, GameMode } from "@minecraft/server";
import * as Vector3 from "../vector3";


export async function onItemUse(event) {
    let player = event.source;
    let cd = player.getItemCooldown("tcs_cwp:tnt_stick");
    if (cd > 0) return;
    let projectileId = "tcs_cwp:tnt_stick_projectile";

    let velocity = 2.8;

    const direction = Vector3.copy(player.getViewDirection());
    const spawnDirection = Vector3.unit(direction);
    const projectileVelocity = direction.multiply(velocity);

    let playerLocation = Vector3.copy(player.location);
    let projectileSpawn = playerLocation.add(Vector3.Up.multiply(1.5)).add(spawnDirection);
    
    const projectile =  player.dimension.spawnEntity(projectileId, projectileSpawn.toLocation());
    let projectileComponent = projectile.getComponent("minecraft:projectile");
    projectileComponent.owner = player;
    projectile.applyImpulse(projectileVelocity.toLocation());
    //game.debug(`view direction: ${Vector3.copy(player.getViewDirection()).toCommand()}` );
    //game.debug(`projectile direction: ${spawnDirection.toCommand()}` );
    //game.debug(`projectile impulse: ${projectileVelocity.toCommand()}` );

    let gameMode = player.getGameMode();
    if(gameMode == GameMode.survival) {
        const inv = player.getComponent(EntityComponentTypes.Inventory);
        const container = inv.container;
        const slot = player.selectedSlotIndex;
        const stack = inv.container.getItem(slot);
        const next = stack.amount - 1;
        if (next <= 0) {
            // remove the item when it reaches zero
            container.setItem(slot, undefined);
        } else {
            stack.amount = next;
            container.setItem(slot, stack);
        }
    }

    player.startItemCooldown("tcs_cwp:tnt_stick", 20);
}