import { EntityComponentTypes, system, world } from "@minecraft/server"

const linkedEntities = new Map()
const linkedOwners = new Map()

export class EntityAPI {
  constructor(visualEntityType) {
    this.visualEntityType = visualEntityType
  }

  Start() {
    system.runInterval(() => {
      for (const player of world.getAllPlayers()) {
        this.HandleEntity(player)
      }
    })
  }

  HandleEntity(player) {
    if (linkedEntities.has(player.id)) {
      const entity = linkedEntities.get(player.id)
      if (!entity) return

      const viewVector = player.getViewDirection()
      let distance = player.isSprinting ? 1.8 : 1
      distance += player.inputInfo.getMovementVector().y * 1

      const lateralVector = { x: -viewVector.z, z: viewVector.x }
      let lateralOffset = 0
      if (Math.abs(player.inputInfo.getMovementVector().x) > 0)
        lateralOffset =
          player.inputInfo.getMovementVector().x > 0 ? -1.15 : 1.15

      const newOffset = {
        x:
          player.location.x +
          viewVector.x * distance +
          lateralVector.x * lateralOffset,
        y: player.location.y + 1.1,
        z:
          player.location.z +
          viewVector.z * distance +
          lateralVector.z * lateralOffset
      }

      entity.teleport(newOffset)
      return
    }

    const entity = player.dimension.spawnEntity(
      this.visualEntityType,
      player.location
    )
    entity.getComponent(EntityComponentTypes.Tameable)?.tame(player)
    linkedEntities.set(player.id, entity)
    linkedOwners.set(entity.id, player.id)
  }

  RemoveEntity(player) {
    const entity = linkedEntities.get(player.id)
    if (entity) {
      entity.remove()
      linkedOwners.delete(entity.id)
      linkedEntities.delete(player.id)
    }
  }
}
