local class = require("core.class")
local state = require("ai.state")
local positioning = require("behavior.positioning")
local locomotion = require("creature.locomotion")
local InCombat = class.Class("InCombat", state.State)
function InCombat:Update(ai, global, constants)
  self:UpdateCombat(ai, global, constants)
  self:UpdateMotion(ai, global, constants)
end
function InCombat:UpdateCombat(ai, global, constants)
  local dTreeParams = {
    DecisionTree = global.DTree,
    AggressiveStandardRecoveryTime = 0,
    NonAggressiveStandardRecoveryTime = 1
  }
  constants.fightKnowledgeInputs.CurrentZoneSet = constants.CurrentZoneSet or "Default"
  if self.OnUpdateCombat then
    self:OnUpdateCombat(ai, global, constants, dTreeParams)
  end
  ai:RunDTree(dTreeParams)
  ai:SetFightIntent(global.fightConstants)
  positioning.SubmitInputs(ai, constants.fightKnowledgeInputs)
  if not constants.DisableFacingTarget then
    ai:SetCombatTarget(global.target)
    ai:SetFocus(global.target)
  end
end
function InCombat:UpdateMotion(ai, global, constants)
  local fightPosition = positioning.GetResult(ai)
  if fightPosition ~= nil then
    local toTarget = global.target:GetWorldPosition() - ai:GetWorldPosition()
    local actuatorData = {
      Destination = fightPosition.Position,
      Speed = fightPosition.SelectedSpeed or "Default",
      Facing = toTarget:Normalized(),
      StopDistance = global.navData.stopDistance,
      StartDistance = global.navData.startDistance,
      Strafe = global.navData.isStrafing
    }
    local avoidanceArgs = {
      AlwaysAvoid = not ai:IsInNavigationMove(),
      GoalPosition = actuatorData.Destination
    }
    if self.OnUpdateMotion then
      self:OnUpdateMotion(ai, global, constants, actuatorData, avoidanceArgs)
    end
    locomotion.SetActuator(ai, actuatorData)
    ai:SetAvoidanceInput({
      Obstacle = {
        Position = ai:GetWorldPosition(),
        Radius = 0.5
      }
    })
  end
end
function InCombat:Exit(ai, global, constants)
  ai:ClearFocus()
end
return {InCombat = InCombat}
