import { world, system, EntityComponentTypes } from "@minecraft/server";
import V3 from "../utilities/V3";

world.beforeEvents.worldInitialize.subscribe((eventData) => {
  const { blockComponentRegistry, itemComponentRegistry } = eventData;

  itemComponentRegistry.registerCustomComponent("cyd_dino:slingshot", {
    onUse(event) {
      const player = event.source
      const inventory = player.getComponent('minecraft:inventory')?.container
      if (!inventory) return

      let ammoSlot = -1
      for (let i = 0; i < inventory.size; i++) {
        const item = inventory.getItem(i)
        if (item && item.typeId === 'cyd_dino:dino_tooth' && item.amount > 0) {
          ammoSlot = i
          break
        }
      }

      if (ammoSlot === -1) {
        player.playSound('random.click')
        return
      }

      const ammoItem = inventory.getItem(ammoSlot)
      const newAmount = ammoItem.amount - 1

      if (newAmount > 0) {
        const updatedItem = ammoItem.clone()

        updatedItem.amount = newAmount
        inventory.setItem(ammoSlot, updatedItem)
      } else inventory.setItem(ammoSlot, undefined)

      spawnProjectile(player)
    },
  });
});

function spawnProjectile(player) {
  const spawnLocation = player.getHeadLocation()

  system.run(() => {
    const proj = player.dimension.spawnEntity("cyd_dino:proj_slingshot", spawnLocation)
    const playerViewDirection = new V3(player.getViewDirection())
    const projComp = proj.getComponent(EntityComponentTypes.Projectile)

    projComp.owner = player
    projComp.shoot(playerViewDirection.scale(1.8))
  })
}

world.afterEvents.projectileHitEntity.subscribe((eventData) => {
  const { source, projectile } = eventData;

  if (projectile.typeId != "cyd_dino:proj_slingshot") return;
  try {
    projectile.remove();
  } catch ($) {
    system.clearRun(runtimer);
  }
});