local class = require("core.class")
local statemachine = require("ai.statemachine")
local unaware = require("awareness.unaware")
local locomotion = require("creature.locomotion")
local Wander = class.Class("Wander_Base", unaware.Unaware) .. {}
function Wander:init()
  self.actuatorParams = {}
  self.StopDistance = self.StopDistance or 2
  self.StopDistance = self.StartDistance or 3
  self.ArrivalDistance = self.ArrivalDistance or 3
  self.Radius = self.Radius or 10
  self.LoiterTime = self.LoiterTime or 4
  self.LoiterTimeVariance = self.LoiterTimeVariance or 1.5
end
function Wander:Enter(ai, global, constants)
  unaware.Unaware.Enter(self, ai, global, constants)
  self.ApproachSpeed = global.navData.navSpeedWalk or 5
  self.spawnPos = ai.SpawnPosition
  self.pos = self.spawnPos and game.NavMesh.ClosestLocation(self.spawnPos, ai)
  if not self.pos then
    engine.Print("WARNING -- AI ", ai:GetName(), " entered Wander without available navmesh.")
  end
end
function Wander:Update(ai, global, constants)
  unaware.Unaware.Update(self, ai, global, constants)
  if self.pos ~= true then
    return
  end
  local myPos = ai:GetWorldPosition()
  if not self.destination then
    local radius = self.Radius
    self.destination = self.pos:FindConnectedLocationInRadius(radius)
  end
  if self.destination then
    self.actuatorParams.Position = self.destination
    self.actuatorParams.StopDistance = self.StopDistance
    self.actuatorParams.ApproachSpeed = self.ApproachSpeed
    locomotion.SetActuator(ai, {
      Destination = self.actuatorParams.Position,
      Facing = self.actuatorParams.Facing,
      Strafe = self.actuatorParams.Strafe,
      Speed = self.actuatorParams.ApproachSpeed,
      StopDistance = self.actuatorParams.StopDistance
    })
    if (myPos - self.destination).length <= self.ArrivalDistance and not self.arrived then
      self.arrived = true
      statemachine.AttachedTimer(self.LoiterTime + math.random(-1 * self.LoiterTimeVariance, self.LoiterTimeVariance), function()
        self.destination = nil
      end)
    end
  end
end
function Wander:Exit(ai, global, constants)
  unaware.Unaware.Exit(self, ai, global, constants)
  self.destination = nil
end
return {Wander = Wander}
