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

function normalize(vec) {
  const length = Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
  return length === 0
    ? { x: 0, y: 0, z: 0 }
    : { x: vec.x / length, y: vec.y / length, z: vec.z / length };
}

world.afterEvents.dataDrivenEntityTrigger.subscribe((data) => {
  const { eventId, entity } = data

  if (eventId === "cyd_dino:trigger_melee" && entity.typeId === "cyd_dino:brachio") {
    const radius = 10

    const origin = entity.location

    system.runTimeout(() => {
      for (const nearby of entity.dimension.getEntities({
        location: origin,
        maxDistance: radius,
        excludeFamilies: ["player"],
      })) {
        if (nearby.typeId == "cyd_dino:brachio") continue
        nearby.applyDamage(4)
      }
    }, 20 * 1)

    return
  }

  if (eventId === 'cyd_dino:trigger_ranged' && entity.getComponent('type_family')?.hasTypeFamily('crossbow_att')) {
    spawnProjectile(entity)

    return
  }
})

function spawnProjectile(entity = Entity.prototype) {
  const spawnLocation = entity.getHeadLocation()

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

    projComp.owner = entity
    projComp.gravity = 0.0001
    projComp.shoot(playerViewDirection.scale(1.8))
  })
}