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


export async function onItemUse(event) {
	let player = event.source;
	let itemId = event.itemStack.typeId;
	let cd = player.getItemCooldown("tcs_cwp:amethyst_staff");
	if (cd > 0) return;
    let projectileId = "tcs_cwp:amethyst_staff_projectile";

    player.startItemCooldown("tcs_cwp_amethyst_staff_animation_shoot", 5.3);
    player.runCommandAsync(`playanimation @s animation.tcs_cwp.amethyst_staff.shoot.tp`);
    
	let shootAngle = [ 0 ];
    let velocity = 2.8;

	utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=3]`, 'tcs_cwp:amethyst_staff_use');
	utils.playSound(player, `@a[x=${player.location.x}, y=${player.location.y}, z=${player.location.z}, r=3]`, 'tcs_cwp:amethyst_staff_throw');

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

	damageItem(player, EquipmentSlot.Mainhand, 1);
	player.startItemCooldown("tcs_cwp:amethyst_staff", 40);
}

export async function onEntityHit(event) {
	const attacker = event.damagingEntity;
	if (!attacker || attacker.typeId !== "minecraft:player") return;

	const heldItem = attacker
		.getComponent("minecraft:equippable")
		?.getEquipment(EquipmentSlot.Mainhand);
	if (!heldItem || heldItem.typeId !== "tcs_cwp:amethyst_staff") return;

	// Punch animations
	attacker.startItemCooldown("tcs_cwp_vampire_fang_punch", 8);
	attacker.playAnimation("animation.tcs_cwp.staff.tp_hit");
}