local LD = require("design.LevelDesignLibrary")
local EC = require("design.Encounter")
local thisObj, thisLevel
local goblinSpawned = false
local goblinKilled = false
local GoblinKilledCallbacks, rarity, goblinRef, spawnPositions, goblinEncounter
local active = false
local DELAY_BETWEEN_SPAWNS = 3
function OnScriptLoaded(level, obj)
  thisLevel = level
  thisObj = obj
  spawnPositions = level:FindGameObjects(obj:FindLuaTableAttribute("GoblinSpawnerList") .. "*")
  rarity = obj:FindLuaTableAttribute("Rarity")
  GoblinKilledCallbacks = obj:FindLuaTableAttribute("GoblinKilledCallbacks")
  if GoblinKilledCallbacks ~= nil and GoblinKilledCallbacks ~= "" then
    GoblinKilledCallbacks = LD.ExtractCallbacksForEvent(thisLevel, obj, GoblinKilledCallbacks)
  else
    GoblinKilledCallbacks = nil
  end
  SetupGoblinEncounter()
  game.SubObject.Sleep(obj)
end
function SetupGoblinEncounter()
  goblinEncounter = EC.NewEncounter(thisLevel, "Goblin (" .. thisLevel.Name .. ")", {CheckpointOnComplete = false})
  goblinEncounter:AddWave({
    spawnPattern = "Random",
    {
      spawners = {
        thisObj:FindSingleGOByName("GoblinSpawner").Child
      },
      spawnLocators = spawnPositions,
      useSpawnLocatorsOnly = true,
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  goblinEncounter:OnEnemySpawn(OnGoblinSpawned)
end
function OnStart(level, obj)
  if goblinSpawned == true and active == true then
    goblinEncounter:Restart()
  end
end
function OnGoblinSpawned(goblin)
  goblinSpawned = true
  if goblinRef ~= nil then
    goblinRef:Destroy()
  end
  goblinRef = goblin
  goblin:CallScript("AssignControllerData", thisObj, rarity, true)
end
function OnGoblinEscape(obj)
  LD.CallFunctionAfterDelay(function()
    if goblinSpawned == true and goblinKilled == false and active then
      goblinEncounter:Restart()
    end
  end, DELAY_BETWEEN_SPAWNS)
end
function OnGoblinDeath(obj)
  goblinSpawned = false
  goblinKilled = true
  active = false
  LD.ExecuteCallbacksForEvent(thisLevel, thisObj, GoblinKilledCallbacks, "GoblinKilledCallbacks")
  goblinEncounter:SetComplete()
  game.SubObject.SoftSave(thisObj)
end
function SpawnEnemy(level)
end
function ActivateGoblin()
  active = true
  if goblinKilled == false then
    goblinEncounter:Restart()
  end
end
function DeactivateGoblin()
  if active then
    active = false
    goblinSpawned = false
    if goblinRef ~= nil then
      goblinRef:CallScript("TriggerEscape")
    end
    if goblinKilled == false then
      goblinEncounter:ForceReset()
    end
  end
end
function OnSaveCheckpoint(level, obj)
  return {
    goblinSpawned = goblinSpawned,
    goblinKilled = goblinKilled,
    active = active
  }
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  goblinSpawned = savedInfo.goblinSpawned or false
  goblinKilled = savedInfo.goblinKilled or false
  active = savedInfo.active or false
end
