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

const darts = [
    {name: "pu_sg:dart", projectile: "pu_sg:dart_projectile", dummy_projectile: "pu_sg:dart_dummy"},
    {name: "pu_sg:poison_dart", projectile: "pu_sg:poison_dart_projectile", dummy_projectile: "pu_sg:dart_poison_dummy"},
]

function getDartByName(name) {
    for (let dart of darts) {
        if (dart.name === name) {
            return dart;
        }
    }
    return null;
}

export async function onItemUse(event) {
  const item = event.itemStack;
  if (item && item.typeId === "pu_sg:sarbacane") {
      const player = event.source;
      const dimension = player.dimension;
      const direction = Vector3.fromRotation(player.getRotation());
      
      let playerLocation = new Vector3.Vector3(player.location);
      let projectileSpawn = playerLocation.add(Vector3.Up.multiply(1.7)).add(direction.multiply(1));
      
      const currentDart = await getCurrentDart(player);
      if (currentDart === null) {
          utils.runPlayerCommand(player, "titleraw @s actionbar {\"rawtext\":[{\"translate\":\"pu_sg_no_dart.text\"}]}");
          return;
      }
      utils.runPlayerCommand(player, "playsound pu_sg:sarbacane_shoot @a[r=7] ~ ~ ~");  

      const dart = getDartByName(currentDart);

      const projectile =  dimension.spawnEntity(dart.dummy_projectile, {x:projectileSpawn.x, y:projectileSpawn.y, z:projectileSpawn.z});
      const projectileVelocity = direction.multiply(2);
      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
      };

      let remove = false;

      if (viewDirection.y < -0.85) {
        remove = true;
      }

      ////////////////////////////////////////////////////////////////////////
      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.7; // Adjust this value for how far right you want
      const adjustedLocation = {
          x: playerLocation.x + rightDirection.x * offset + viewDirection.x,
          y: playerLocation.y + 1.5, // Spawn above the player's head
          z: playerLocation.z + rightDirection.z * offset + viewDirection.z
      };

      const summonCommand = `summon ${dart.projectile} ${adjustedLocation.x} ${adjustedLocation.y} ${adjustedLocation.z} facing ${facingLocation.x} ${facingLocation.y} ${facingLocation.z}`;
      try {
          dimension.runCommand(summonCommand);
          utils.runPlayerCommand(player, `clear @s ${currentDart} 0 1`);
        } catch (error) {
            return;
        }
      const dummy = dimension.getEntities({
          type: dart.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()) {
            try {
                if (remove === false){
                    system.runTimeout(() => { if (dummy && dummy.isValid()) dummy?.remove(); }, 7);
                } else {
                    if (dummy && dummy.isValid()) dummy?.remove();
                }
            } catch (error) {
            }
              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
          });

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



      // Handle durability
      if (item.getComponent("minecraft:durability").damage < (item.getComponent("minecraft:durability").maxDurability - 1)) {
          const newItem = await item.clone();
          newItem.getComponent("minecraft:durability").damage = item.getComponent("minecraft:durability").damage + 1;
          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.damagingProjectile;
    const entity = event.hurtEntity;
    if (source?.typeId === "pu_sg:dart_poison_dummy") {
        if(entity.isValid()){
            utils.runEntityCommand(entity, "effect @s poison 2 1");
        }
    }
}

// Helper function to get the current orb type in inventory
async function getCurrentDart(player) {
    const InvComponent = player.getComponent("minecraft:inventory");
    if (!InvComponent) return null;
  
    const inventory = InvComponent.container;
  
    for (let i = 0; i < inventory.size; i++) {
      let item = inventory.getItem(i);
      if (item && item.typeId.endsWith("dart")) {
        return item.typeId; 
      }
    }
    return null;
}

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:sarbacane"){
            player.playAnimation("animation.pu_sg.sarbacane.player_arm");
          }
        }
      }
    }
  } catch (e) {
  }
}