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

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

  itemComponentRegistry.registerCustomComponent("cyd_dino:net_crossbow", {
    onUse(e) {
      spawnProjectile(e.source);
    },
  });
});

function spawnProjectile(player) {
  const spawnLocation = player.getHeadLocation();
  system.run(() => {
    const proj = player.dimension.spawnEntity("cyd_dino:net", spawnLocation);
    const playerViewDirection = new V3(player.getViewDirection());
    proj.addEffect("slow_falling", 1000, {
      amplifier: 1,
      showParticles: false,
    });
    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:net") return;

  projectile.clearVelocity();

  if (!eventData.getEntityHit()) return
  const entityHit = eventData.getEntityHit()
  if (!entityHit.entity.typeId.startsWith('cyd_dino:')) return

  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);
})