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

const Velocity = 1.5;
//let shootingInProgress = false;
export async function onItemUse(event)
{
	const item = event.itemStack.typeId;
	if (item != "goe_bos:boss_bone_blade")
		return;
	
	const shooter = event.source;
	const direction = Vector3.fromRotation(shooter.getRotation());
	
	let playerLocation = new Vector3.Vector3(shooter.location);
	const viewDirection = shooter.getViewDirection();
	const facingLocation = {
        x: playerLocation.x + viewDirection.x,
        y: playerLocation.y + viewDirection.y,
        z: playerLocation.z + viewDirection.z
    };
	let projectileSpawn = playerLocation.add(Vector3.Up.multiply(1.5)).add(direction.multiply(2));
	
	
	const projectile =  shooter.dimension.spawnEntity("goe_bos:slash_projectile", {x:projectileSpawn.x, y:projectileSpawn.y, z:projectileSpawn.z});
	const projectileVelocity = direction.multiply(Velocity);
    utils.runPlayerCommand(shooter, "playsound goe_bos:boss_bone_breaker_slash @s ~ ~ ~");

	const summonCommand = `summon goe_bos:slash ${playerLocation.x} ${playerLocation.y} ${playerLocation.z} facing ${facingLocation.x} ${facingLocation.y} ${facingLocation.z}`;
    try {
        shooter.dimension.runCommand(summonCommand);
    } catch (error) {
        console.error("Failed to summon the slash_projectile projectile:", error);
        return;
    }
	const dummy = shooter.dimension.getEntities({
        type: "goe_bos:slash",
        location: playerLocation,
        maxDistance: 5
    })[0];

	projectile.applyImpulse({x: projectileVelocity.x, y:projectileVelocity.y, z: projectileVelocity.z});

	let inc = 1;


    const runId = system.runInterval(() => {
        if (!dummy || !dummy.isValid()) {
            system.clearRun(runId);
            return;
        }
        if (!projectile || !projectile.isValid()) {
            system.clearRun(runId);
            return;
        }

        const projectileLocation = projectile.location;
        const facingLocation = {
            x: projectileLocation.x + viewDirection.x,
            y: projectileLocation.y + viewDirection.y,
            z: projectileLocation.z + viewDirection.z
        };
        dummy.teleport(projectileLocation, {
            facingLocation: facingLocation
        });

        if (inc > 100) {
            system.clearRun(runId);
        }
        inc++;
    }, 1);

	utils.runPlayerCommand(shooter, `playanimation @s animation.goe_bos.player.throw_sword animation.goe_bos.player.empty 0 v.is_first_person`);
}