local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local color = require("core.color")
local monitors = require("level.MonitorLibrary")
local EC = require("design.Encounter")
local uiCalls = require("ui.uicalls")
local delayTimers = require("level.timer")
local thisLevel, Area_2_Encounter_1, Area_2_Encounter_2
local Rift_Challenge_Duration = 180
local Challenge_Started = false
local ecTimer, ec_TimeRequirement, hudTimeRemaining
local delayDestruction = false
local delayDestruction_T = {}
function OnScriptLoaded(level)
  thisLevel = level
  Area_2_Fight_1()
  if game.GetNewGamePlus() then
    New_Game_Plus_Foot_Tower_Rift_1()
  else
    Foot_Tower_Rift_1()
  end
end
function OnFirstStart(level)
  GameObjects.RespawnRiftSafety:HideEntityVolume()
end
function OnStart(level)
  GameObjects.CrawlerSpitSpawnZone:HideEntityVolume()
end
function OnUpdate(level, obj)
  UpdateCreatureDestruction()
  if Challenge_Started then
    Encounter_Timer()
  end
end
function RespawnRiftFight()
  if Area_2_Encounter_2 ~= nil and not Area_2_Encounter_2:IsComplete() and not Area_2_Encounter_2:IsRunning() then
    GameObjects.LootPocketRiftCal250.LuaObjectScript.ResetCombatState()
  end
end
function CrawlerSpitOn()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 182 <= completedCineNumber and completedCineNumber < 184 then
    GameObjects.CrawlerSpitSpawnZone:ShowEntityVolume()
  end
end
function CrawlerSpitOff()
  local completedCineNumber = game.Level.GetVariable("CompletedCineNumber")
  if 182 <= completedCineNumber and completedCineNumber < 184 then
    GameObjects.CrawlerSpitSpawnZone:HideEntityVolume()
  end
end
function Area_2_Fight_1()
  Area_2_Encounter_1 = EC.NewEncounter(thisLevel, "[Area 1]EC:Crawler Emerges Fight", {
    CheckpointOnComplete = false,
    spawnWad = "Cal100_AI_01"
  })
  Area_2_Encounter_1:AddWave({
    {
      spawners = "Crawler_SpitBandit",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 1
    }
  })
  Area_2_Encounter_1:SetStartZone(GameObjects.CrawlerSpitSpawnZone, {
    cineRequirement = {182, 184}
  })
  Area_2_Encounter_1:OnStart(function()
    game.Audio.PlayBanter("CrawlerIntro")
  end)
  Area_2_Encounter_1:OnComplete(function()
    LD.UnlockBestiaryEntry_EndOfEncounter("Bestiary_Unlock_Tatzelwurm_Stinger")
  end)
end
function StartFightRiftFootTower()
  GameObjects.RespawnRiftSafety:ShowEntityVolume()
  timers.StartLevelTimer(2, function()
    Area_2_Encounter_2:Start()
  end)
  timers.StartLevelTimer(5, function()
    GameObjects.LootPocketRiftCal250.LuaObjectScript.SpawningDone()
  end)
end
function StopFightRiftFootTower()
  GameObjects.LootPocketRiftCal250.LuaObjectScript.StopCombatState()
  GameObjects.RespawnRiftSafety:HideEntityVolume()
  local cal250 = game.FindLevel("Cal250_FootHillsLH")
  cal250:CallScript("Set250FightVarComplete")
end
function PlaySoundEnemySpawnRiftFootTower()
  GameObjects.LootPocketRiftCal250.LuaObjectScript.PlaySoundCombatPortalEnemySpawn()
end
function Foot_Tower_Rift_1()
  Area_2_Encounter_2 = EC.NewEncounter(thisLevel, "[Area 2]EC:4 Foothills LoadHall Poison Rift", {
    CheckpointOnComplete = true,
    LoadCheck = true,
    LeashZone = "LeashCal250"
  })
  Area_2_Encounter_2:AddWave({
    {
      spawners = "Witch_6_RIFT",
      spawnWad = "Cal250_FootHillsLH_AI_Visit02",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      spawners = "Witch_7_RIFT",
      spawnWad = "Cal250_FootHillsLH_AI_Visit02",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 3.5
    }
  })
  Area_2_Encounter_2:OnEnemySpawn(PlaySoundEnemySpawnRiftFootTower)
  Area_2_Encounter_2:OnComplete(StopFightRiftFootTower)
  Area_2_Encounter_2:OnComplete(function()
    LD.SetMarkerState("CAL_100_FootTowerFight", 0)
  end)
end
function New_Game_Plus_Foot_Tower_Rift_1()
  Area_2_Encounter_2 = EC.NewEncounter(thisLevel, "[Area 2]EC:4 NPlus Foothills LoadHall Poison Rift", {
    CheckpointOnComplete = true,
    LoadCheck = true,
    LeashZone = "LeashCal250"
  })
  Area_2_Encounter_2:AddWave({
    {
      spawners = "Witch_6_RIFT",
      spawnWad = "Cal250_FootHillsLH_AI_Visit02",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    },
    {
      spawners = "Witch_7_RIFT",
      spawnWad = "Cal250_FootHillsLH_AI_Visit02",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 3.5
    }
  })
  Area_2_Encounter_2:OnStart(function()
    Set_Encounter_Timer(90, Area_2_Encounter_2)
    Start_Timer()
  end)
  Area_2_Encounter_2:OnEnemySpawn(PlaySoundEnemySpawnRiftFootTower)
  Area_2_Encounter_2:OnEnemySpawn(function(enemy)
    enemy:ForceMove("MOV_SetDontDropLootFlag_On")
  end)
  Area_2_Encounter_2:OnComplete(StopFightRiftFootTower)
  Area_2_Encounter_2:OnComplete(function()
    LD.SetMarkerState("CAL_100_FootTowerFight", 0)
    Event_Complete()
  end)
end
function Set_Encounter_Timer(timeRequirement)
  ec_TimeRequirement = timeRequirement
  ecTimer = StartLevelTimer(timeRequirement, EventFailed_TimeElapsed)
  ecTimer:Stop()
end
function Start_Timer()
  local startDelay = 1
  Challenge_Started = true
  LD.CallFunctionAfterDelay(function()
    ecTimer:Start()
  end, startDelay)
  hudTimeRemaining = math.floor(ec_TimeRequirement - ecTimer.time)
  local seconds = ec_TimeRequirement % 60
  local minutes = (hudTimeRemaining - seconds) / 60
  local Time_Text = string.format("%02d : %02d", minutes, seconds)
end
function Encounter_Timer()
  hudTimeRemaining = math.floor(ec_TimeRequirement - ecTimer.time)
  local seconds = hudTimeRemaining % 60
  local minutes = (hudTimeRemaining - seconds) / 60
  local Time_Text = string.format("%02d : %02d", minutes, seconds)
  uiCalls.EnableMechanicText(37906, {minutes, seconds})
end
function EventFailed_TimeElapsed()
  local seconds = Rift_Challenge_Duration % 60
  local minutes = Rift_Challenge_Duration / 60
  local Time_Text = string.format("%02d : %02d", minutes, seconds)
  uiCalls.DisableMechanicText()
  Despawn_Enemy_VFX(Area_2_Encounter_2)
  Area_2_Encounter_2:Reset()
  Area_2_Encounter_2:Stop()
  ResetRift_Callback()
  ecTimer:Stop()
  ecTimer:Reset()
  Challenge_Started = false
end
function Event_Complete()
  uiCalls.DisableMechanicText()
  ecTimer:Stop()
  ecTimer:Reset()
  Challenge_Started = false
end
function Despawn_Enemy_VFX(encounter)
  local minTime = 0.01
  local maxTime = 0.3
  local randomFn = function()
    return math.random(minTime * 1000, maxTime * 1000) / 1000
  end
  local enemies = encounter:GetActiveEnemies()
  for _, enemy in pairs(enemies) do
    if enemy ~= nil and enemy:IsDoingSyncMove() == false then
      timers.StartLevelTimer(randomFn(), function()
        if enemy ~= nil then
          SpawnFXAtCreatureLocation(enemy)
          enemy:Destroy()
        end
      end)
      CreatureInSyncMove_DelayDestruction(enemy)
    end
  end
  encounter:ResetLivingEnemiesCount()
  encounter:ReportWaveDespawned(nil)
end
function SpawnFXAtCreatureLocation(creature)
  local fx = game.FX.Spawn("Body_Fire_Explode", nil, {
    AutoDelete = true,
    EffectCreator = creature,
    Scale = 1.5
  })
  local lastEnemyPos = creature:GetWorldJointPosition(creature:GetJointIndex("JOPelvis1"))
  fx:SetWorldPosition(lastEnemyPos)
end
function CreatureInSyncMove_DelayDestruction(creature)
  delayDestruction = true
  delayDestruction_T[creature] = true
end
function UpdateCreatureDestruction()
  if delayDestruction == true then
    local remaining = 0
    for creature, _ in pairs(delayDestruction_T) do
      if creature ~= nil and delayDestruction_T[creature] == true then
        if creature:IsDoingSyncMove() == false then
          SpawnFXAtCreatureLocation(creature)
          creature:Destroy()
          delayDestruction_T[creature] = nil
        else
          remaining = remaining + 1
        end
      end
    end
    if remaining == 0 then
      delayDestruction = false
      delayDestruction_T = {}
    end
  end
end
function ResetRift_Callback()
  GameObjects.LootPocketRiftCal250.LuaObjectScript.ResetCombatState()
end
