local statemachine = require("ai.statemachine")
local tablex = require("core.tablex")
local picklelib = require("core.pickle")
local DL = require("design.DesignerLibrary")
local LDL = require("design.LevelDesignLibrary")
local components = require("design.components")
local timer = require("creature.timer")
local monitors = require("level.MonitorLibrary")
attachments = {}
local Brain_Core = require("behavior.corebrain")
constants = {}
global = {}
local ESCAPE_TIME_UPPER_LIMIT = {
  common = 0.25,
  rare = 0.5,
  legendary = 0
}
local DISTANCE_FROM_PLAYER_TO_TRIGGER_ESCAPE = 3.5
local EscapeStarted = false
local escapeTimer
local broadcastFX_Spawn_Started = false
local portalFX, Controller, Rarity
local IsActive = false
local thePlayer
function AssignControllerData(ai, newController, rarity, isActive)
  Controller = newController
  Rarity = rarity
  IsActive = isActive
end
function OnAIPostSpawn(ai)
  thePlayer = game.Player.FindPlayer()
end
function OnAIUpdate(ai)
  components.UpdateComponents(ai, attachments)
  if escapeTimer == nil and thePlayer and thePlayer.ReticleTargetCreature == ai and Controller and IsActive then
    escapeTimer = ESCAPE_TIME_UPPER_LIMIT[Rarity]
  end
  if Controller ~= nil and EscapeStarted == false then
    local distanceToPlayer = game.AIUtil.Distance(ai, thePlayer)
    if distanceToPlayer < DISTANCE_FROM_PLAYER_TO_TRIGGER_ESCAPE and ai:IsPlayingMove("MOV_Spawn") == false then
      TriggerEscape(ai)
    end
    if escapeTimer ~= nil then
      if 0 < escapeTimer then
        escapeTimer = escapeTimer - ai:GetFrameTime()
      end
      if escapeTimer <= 0 then
        TriggerEscape(ai)
      end
    end
  end
end
function TriggerEscape(ai)
  ai:TriggerMoveEvent("LE_Escape")
  escapeTimer = nil
  EscapeStarted = true
end
function Brain_Core:Update(ai, global, constants)
  Brain_Core:UpdateAggroState(ai, global)
  Brain_Core:Update(ai, global, constants)
end
function _G.OnAICreateLuaState(ai)
  components.StartComponents(ai, attachments)
  _G.OnAICreateLuaState = nil
end
picklelib.Install()
function Pickle(GO)
  return {
    global = global
  }
end
function Unpickle(GO, t)
  global = t.global
end
function LuaHook_GoblinEscaped(ai, data)
  if Controller then
    Controller:CallScript("OnGoblinEscape")
  end
  ai:Destroy()
end
function LuaHook_GoblinDeath(ai, data)
  if Controller then
    Controller:CallScript("OnGoblinDeath")
  end
end
