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

export async function onItemUse(event) {
    const item = event.itemStack;
    if (item.typeId === "pu_sg:alien_blaster") {
        const player = event.source;
        utils.runPlayerCommand(player, "playsound pu_sg:alien_blaster_shoot @a[r=7] ~ ~ ~");  
        const entities = player.getEntitiesFromViewDirection({ maxDistance: 512 });
        const damage = 4;
        system.runTimeout(() => {
            for (const e of entities) {
                const entity = e.entity;
                if(entity.typeId === "minecraft:item") continue;
                if (!entity || !entity.isValid()) continue;
                entity.applyDamage(damage, { damagingEntity: player, cause: EntityDamageCause.fire });
            }
        }, 5);

        const vel = utility.divideVector(utility.normalizeVector3D(player.getViewDirection()), 32);
        let loc = player.getHeadLocation();

        const viewDir = player.getViewDirection(); // Get the player's view direction

        // Calculate the right direction relative to the player's view
        const upVector = { x: 0, y: 1, z: 0 }; // World up vector
        const rightDir = utility.crossProduct(viewDir, upVector); // Get the right vector relative to view direction

        // Adjustments for positioning
        const rightAdjust = 0.15;  // Moves particles to the right
        const upAdjust = 0.05;    // Moves particles upward
        const forwardAdjust = 0.6; // Moves particles forward (in depth) relative to the player's view direction

        // Apply the right, upward, and forward adjustments
        loc.x += rightDir.x * rightAdjust + viewDir.x * forwardAdjust;
        loc.y += upAdjust + viewDir.y * forwardAdjust;
        loc.z += rightDir.z * rightAdjust + viewDir.z * forwardAdjust;
        for (let i = 0; i < 512; i++) {
            const bl = player.dimension.getBlock(loc);
            if (!bl || !bl.isValid() || (!bl.isAir && !bl.isLiquid)) break;
            system.runTimeout(() => {
            try {
                player.dimension.spawnParticle("pu_sg:alien_blaster_3", loc);
            } catch (error) {
            }
            loc = utility.addVectors(loc, vel);
            },i/25);
        }
    }
}

export async function onTick()
{
  try {
    for (const player of world.getPlayers()) {
        const equippable = player.getComponent('equippable');
        if(equippable){
            const mainhand = equippable.getEquipment(EquipmentSlot.Mainhand);
            if(mainhand){
              if(mainhand.typeId == "pu_sg:alien_blaster"){
                player.playAnimation('animation.pu_sg.sarbacane.player_arm');
              }
            }
        }
    }
  } catch (e) {
  }
}
