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

export async function onItemUse(event) {
    const player = event.source;
    const item = event.itemStack;
    if (item && (item.typeId === "pu_sg:fire_sword" || item.typeId === "pu_sg:fireball")) {
        const dimension = player.dimension;
        //Spawn Projectile
        utils.runPlayerCommand(player, "playsound pu_sg:fireball_throw @a[r=7] ~ ~ ~");   
        const direction = Vector3.fromRotation(player.getRotation());
	
        let playerLocation = new Vector3.Vector3(player.location);
        let projectileSpawn = playerLocation.add(Vector3.Up.multiply(2)).add(direction.multiply(2));
    
        const projectile =  dimension.spawnEntity("pu_sg:dummy_projectile", {x:projectileSpawn.x, y:projectileSpawn.y, z:projectileSpawn.z});
        const projectileVelocity = direction.multiply(1.5);
        projectile.applyImpulse({x: projectileVelocity.x, y:projectileVelocity.y, z: projectileVelocity.z});

        const viewDirection = player.getViewDirection();
        const facingLocation = {
            x: playerLocation.x + viewDirection.x,
            y: playerLocation.y + viewDirection.y,
            z: playerLocation.z + viewDirection.z
        };

        ////////////////////////////////////////////////////////////////////////
        const rightDirection = {
            x: -viewDirection.z,
            y: 0, // No vertical offset for right direction
            z: viewDirection.x
        };
        
        // Adjust the projectile spawn position slightly to the right
        const offset = 0.5; // Adjust this value for how far right you want
        const adjustedLocation = {
            x: playerLocation.x + rightDirection.x * offset,
            y: playerLocation.y + 0.7, // Spawn above the player's head
            z: playerLocation.z + rightDirection.z * offset
        };

        const summonCommand = `summon pu_sg:fireball_projectile ${adjustedLocation.x} ${adjustedLocation.y} ${adjustedLocation.z} facing ${facingLocation.x} ${facingLocation.y} ${facingLocation.z}`;
        try {
            dimension.runCommand(summonCommand);
            if (item.typeId === "pu_sg:fireball") {
                utils.runPlayerCommand(player, "clear @s pu_sg:fireball 0 1");
            }
        } catch (error) {
            return;
        }

        const dummy = dimension.getEntities({
            type: "pu_sg:fireball_projectile",
            location: playerLocation,
            maxDistance: 5
        })[0];
        let inc = 1;


        const interval = system.runInterval(() => {
            if (!dummy || !dummy.isValid()) {
                system.clearRun(interval);
                return;
            }
            if (!projectile || !projectile.isValid()) {
                system.runTimeout(() => { if (dummy && dummy.isValid()) dummy?.remove(); }, 7);
                system.clearRun(interval);
                return;
            }

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

            // const entitesToDamage = dimension.getEntities({
            //     location: projectileLocation,
            //     maxDistance: 4
            // });
            // for (const entity of entitesToDamage) {
            //     if (entity.typeId !== "pu_sg:dummy_projectile" && entity !== projectile && entity !== player) {
            //         entity.applyDamage(3);
            //     }
            // }

            if (inc > 100) {
                dummy?.remove();
                system.clearRun(interval);
                return;
            }
            inc++;
        }, 1);

        //Hadle Durability
        if (item.typeId === "pu_sg:fire_sword") {
            if (item.getComponent("minecraft:durability").damage < (item.getComponent("minecraft:durability").maxDurability - 3)) {
                const newItem = await item.clone();
                newItem.getComponent("minecraft:durability").damage = item.getComponent("minecraft:durability").damage + 3;
                await player.getComponent("inventory").container.setItem(player.selectedSlotIndex, newItem);
            } else {
                player.playSound('random.break');
                await player.getComponent("inventory").container.setItem(player.selectedSlotIndex, null);
            }
        }
    }
}

export async function onEntityHurt(event) {
    const source = event.damageSource.damagingEntity;
    const entity = event.hurtEntity;
    if (source?.typeId === "minecraft:player") {
        const equippable = source.getComponent('equippable');
        if (!equippable) return;
        const mainhand = equippable.getEquipment(EquipmentSlot.Mainhand);
        if (mainhand?.typeId === 'pu_sg:fire_sword') {
            if(entity.isValid()){
                const dimension = entity.dimension;
                dimension.spawnParticle("pu_sg:fire_sword_1", {x: source.location.x, y: source.location.y + 1, z: source.location.z});
                dimension.spawnParticle("pu_sg:fire_sword_2", {x: entity.location.x, y: entity.location.y + 1, z: entity.location.z});
                dimension.playSound("pu_sg:fire_sword_attack", entity.location);
            }
        }
    }

    if (source?.typeId === "pu_sg:dummy_projectile"){
        entity.setOnFire(2);
    }
}