local CL = require("camera.CameraLibrary")
local kfCameraFightRadius = 30
local playerCreature = game.Player.FindPlayer():GetCreature()
local enemiesFound, enemyTarget
function OnScriptLoaded(level, camera)
end
function OnUpdate(level, camera)
  playerCreature = CL.FindPlayerSafetyCheck(playerCreature)
  enemiesFound = playerCreature:FindEnemies(kfCameraFightRadius)
  enemyTarget = GetClosestEnemy(enemiesFound)
  if enemyTarget ~= nil then
    TargetHeadJoint(enemyTarget)
  end
end
function OnTeardown(level, camera)
end
function GetClosestEnemy(enemiesNearPlayer)
  local playerPosition = game.Player.FindPlayer():GetGameObject():GetWorldPosition()
  local nearestEnemy = {
    id = nil,
    distance = nil,
    position = nil
  }
  for _, thisPlayerEnemy in ipairs(enemiesNearPlayer) do
    local enemyPosition = thisPlayerEnemy:GetWorldPosition()
    local thisEnemyDistanceToPlayer = playerPosition:Distance(enemyPosition)
    if thisPlayerEnemy:IsDead() == false and thisPlayerEnemy:IsDying() == false then
      if nearestEnemy.id == nil then
        nearestEnemy.id = thisPlayerEnemy
        nearestEnemy.distance = thisEnemyDistanceToPlayer
        nearestEnemy.position = enemyPosition
      elseif thisEnemyDistanceToPlayer < nearestEnemy.distance then
        nearestEnemy.id = thisPlayerEnemy
        nearestEnemy.distance = thisEnemyDistanceToPlayer
        nearestEnemy.position = enemyPosition
      end
    end
  end
  if nearestEnemy.id ~= nil then
    print(" The closest dude is " .. tostring(nearestEnemy.id) .. " who is " .. string.format("%f", nearestEnemy.distance) .. "m away and located at " .. string.format("%f", nearestEnemy.position.x) .. ", " .. string.format("%f", nearestEnemy.position.y) .. ", " .. string.format("%f", nearestEnemy.position.z))
    engine.DrawTextInWorld(nearestEnemy.position, " FEAR ME: I AM THE NEAREST", 16711680, 1)
    return nearestEnemy.id
  else
    return nil
  end
end
function TargetHeadJoint(enemyId)
  local headIndex = enemyId:GetJointIndex("JOHead1")
  local headWorldPosition = enemyId:GetWorldJointPosition(headIndex)
  engine.DrawFillSphere(headWorldPosition, 0.2, 267386880)
  engine.DrawTextInWorld(headWorldPosition, "X   X", 0, -2)
  engine.DrawTextInWorld(headWorldPosition, "    ", 0, -1)
  engine.DrawTextInWorld(headWorldPosition, " --- ", 0, 0)
  engine.DrawTextInWorld(headWorldPosition, "/    \\ ", 0, 1)
end
