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:bolas", {
    onUse(e) {
      spawnProjectile(e.source);
    },
  });
});

function spawnProjectile(player) {
  const spawnLocation = player.getHeadLocation();
  system.run(() => {
    const proj = player.dimension.spawnEntity("cyd_dino:proj_bolas", 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_bolas") return;

  projectile.clearVelocity();

  if (!eventData.getEntityHit()) return;

  const entityHit = eventData.getEntityHit();
  entityHit.entity.addEffect("slowness", 15 * 20, {
    amplifier: 255,
    showParticles: true,
  });

  const runtimer = system.runInterval(() => {
    try {
      entityHit.entity.teleport(projectile.location);
    } catch ($) {
      system.clearRun(runtimer);
    }
  }, 0);

  system.runTimeout(() => {
    try {
      projectile.triggerEvent('cyd_dino:despawn')
    } catch ($) { }
  }, 15 * 20);
});

const projectiles = [
  'cyd_dino:proj_bolas',
  'cyd_dino:net'
]

world.afterEvents.entityHitEntity.subscribe((eventData) => {
  const { hitEntity, damagingEntity } = eventData
  if (damagingEntity.typeId != "minecraft:player") return

  if (projectiles.includes(damagingEntity.typeId)) hitEntity.triggerEvent('cyd_dino:despawn')
})

world.afterEvents.entitySpawn.subscribe((eventData) => {
  const { entity } = eventData
  if (!projectiles.includes(entity.typeId)) return

  system.runTimeout(() => { try { entity.triggerEvent('cyd_dino:despawn') } catch ($) { } }, 20 * 20)
})