import { EquipmentSlot, world, Player } from "@minecraft/server";
import { afterEvents, namespace as ns } from "./eternal/constants";
import { runInterval } from "./eternal/utils";

afterEvents.projectileHitEntity.subscribe(({ projectile, location }) => {
  if (projectile.typeId === "ecbl_bc:slingshot.projectile") {
    spawnParticle(projectile, location, "ecbl_bc:stone_breaking");
  }
});

afterEvents.projectileHitBlock.subscribe(({ projectile, location }) => {
  if (projectile.typeId === "ecbl_bc:slingshot.projectile") {
    spawnParticle(projectile, location, "ecbl_bc:stone_breaking");
    projectile.remove();
  }
});

afterEvents.itemStartUse.subscribe(({ itemStack, source: player }) => {
  if (itemStack.typeId === "ecbl_bc:slingshot") {
    if (player.hasSlingshotAmmo) {
      player.playSound("random.ecbl_bc.slingshot.stretch");
    }
  }
});

afterEvents.itemReleaseUse.subscribe(({ itemStack, source: player }) => {
  if (itemStack.typeId === "ecbl_bc:slingshot") {
    if (player.hasSlingshotAmmo) {
      player.stopSound("random.ecbl_bc.slingshot.stretch");
      player.damageItem(EquipmentSlot.Mainhand);
      player.playSound("random.ecbl_bc.slingshot.shoot");
    }
  }
});

afterEvents.itemCompleteUse.subscribe(({ itemStack, source: player }) => {
  if (itemStack.typeId === "ecbl_bc:slingshot") {
    if (player.hasSlingshotAmmo) {
      player.damageItem(EquipmentSlot.Mainhand);
      player.playSound("random.ecbl_bc.slingshot.shoot");
    }
  }
});

function spawnParticle(projectile, location, particleId) {
  try {
    projectile.dimension.spawnParticle(particleId, location);
  } catch (error) {}
}

runInterval(() => {
  const entities = world.getEntities({ type: `${ns}:slingshot.projectile` });

  for (const entity of entities) {
    try {
      entity.dimension.spawnParticle("ecbl_bc:trail", entity.location);
    } catch (error) {}
  }
});

Object.defineProperty(Player.prototype, "hasSlingshotAmmo", {
  get: function () {
    const itemsEq = this.getItems(`${ns}:pile_of_pebbles_item`).equipments;
    const itemsIn = this.getItems(`${ns}:pile_of_pebbles_item`).inventory;
    if (itemsEq.size > 0 || itemsIn.size > 0) {
      return true;
    }
    return false;
  },
});
