local LD = require("design.LevelDesignLibrary")
local timers = require("level.timer")
local monitors = require("level.MonitorLibrary")
local EC = require("design.Encounter")
local DungeonEncounters = require("boss.statemachine")
local uiCalls = require("ui.uicalls")
local thisObj, thisLevel, player, enc_For260_Fight_01, enc_For260_Fight_02, Enemy_HealthMonitor, ChiselAlertWaveZoneMonitor
local Rift_Challenge_Duration = 10
local Challenge_Started = false
local ecTimer, ec_TimeRequirement, hudTimeRemaining
local delayDestruction = false
local delayDestruction_T = {}
function OnScriptLoaded(level, obj)
  thisLevel = level
  player = game.Player.FindPlayer()
  FNC_For260_Fight_01()
  if game.GetNewGamePlus() then
    New_Game_Plus_FNC_For260_Fight_02()
  else
    FNC_For260_Fight_02()
  end
end
function OnUpdate(level)
  UpdateCreatureDestruction()
  if Challenge_Started then
    Encounter_Timer()
  end
end
function TurnOn260RiftMarker()
  LD.SetMarkerState("FOR_260_ChiselFight", 1)
end
function FNC_For260_Fight_02()
  enc_For260_Fight_02 = EC.NewEncounter(thisLevel, "FOR260 Chisel Dungeon Fight 02", {
    CheckpointOnComplete = true,
    LeashZone = "LeashZone260_1",
    StartMusic = "SND_MX_PRO_rift_fight_in",
    StopMusic = "SND_MX_PRO_rift_fight_out"
  })
  enc_For260_Fight_02:AddWave({
    timeBeforeNextWave = 2.25,
    {
      spawners = "WitchRiftSummoner",
      spawnWad = "For260_ChiselDungeon",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0,
      markerID = "SpawnedFromRift_PktRft_A"
    }
  })
  enc_For260_Fight_02:AddWave({
    triggerWaveFromScript = true,
    {
      spawners = "Draugr_Light_PL3_S_SBQ",
      spawnLocators = "Loc_PKRFT_A",
      useSpawnLocatorsOnly = true,
      spawnWad = "For260_ChiselDungeon",
      markerID = "SpawnedFromRift_PktRft_A",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2
    },
    {
      spawners = "Draugr_Hvy_PL3_E_SBQ",
      spawnLocators = "Loc_PKRFT_B",
      useSpawnLocatorsOnly = true,
      spawnWad = "For260_ChiselDungeon",
      markerID = "SpawnedFromRift_PktRft_A",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 4
    }
  })
  enc_For260_Fight_02:OnEnemySpawn(function()
    GameObjects.PktRft_A.LuaObjectScript.PlaySoundCombatPortalEnemySpawn()
  end, {
    markerID = "SpawnedFromRift_PktRft_A"
  })
  enc_For260_Fight_02:OnComplete(function()
    LD.SetMarkerState("FOR_260_ChiselFight", 0)
  end)
  enc_For260_Fight_02:OnStart(function()
    GameObjects.PktRft_A.LuaObjectScript.StartCombatState()
    GameObjects.PktRft_B.LuaObjectScript.StartCombatState()
    timers.StartLevelTimer(8, function()
      GameObjects.PktRft_A.LuaObjectScript.SpawningDone()
    end)
    timers.StartLevelTimer(10, function()
      GameObjects.PktRft_B.LuaObjectScript.SpawningDone()
    end)
  end, 2)
  enc_For260_Fight_02:OnComplete(function()
    _G.SetEncounterComplete()
    _G.CA_Arena_Enable()
    _G.LTW_Lobby_Enable()
    _G.OpenArenaDoors()
    Stop_FightRift()
  end)
end
function New_Game_Plus_FNC_For260_Fight_02()
  enc_For260_Fight_02 = EC.NewEncounter(thisLevel, "FOR260 NPlus Chisel Dungeon Rift", {
    CheckpointOnComplete = true,
    LeashZone = "LeashZone260_1",
    StartMusic = "SND_MX_PRO_rift_fight_in",
    StopMusic = "SND_MX_PRO_rift_fight_out"
  })
  enc_For260_Fight_02:AddWave({
    timeBeforeNextWave = 2.25,
    {
      spawners = "WitchRiftSummoner",
      spawnWad = "For260_ChiselDungeon",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0,
      markerID = "SpawnedFromRift_PktRft_A"
    }
  })
  enc_For260_Fight_02:AddWave({
    triggerWaveFromScript = true,
    {
      spawners = "Draugr_Light_PL3_S_SBQ",
      spawnLocators = "Loc_PKRFT_A",
      useSpawnLocatorsOnly = true,
      spawnWad = "For260_ChiselDungeon",
      markerID = "SpawnedFromRift_PktRft_A",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 2
    },
    {
      spawners = "Draugr_Hvy_PL3_E_SBQ",
      spawnLocators = "Loc_PKRFT_B",
      useSpawnLocatorsOnly = true,
      spawnWad = "For260_ChiselDungeon",
      markerID = "SpawnedFromRift_PktRft_A",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 4
    }
  })
  enc_For260_Fight_02:OnEnemySpawn(function()
    GameObjects.PktRft_A.LuaObjectScript.PlaySoundCombatPortalEnemySpawn()
  end, {
    markerID = "SpawnedFromRift_PktRft_A"
  })
  enc_For260_Fight_02:OnComplete(function()
    LD.SetMarkerState("FOR_260_ChiselFight", 0)
  end)
  enc_For260_Fight_02:OnStart(function()
    Set_Encounter_Timer(60, enc_For260_Fight_02)
    Start_Timer()
  end)
  enc_For260_Fight_02:OnStart(function()
    timers.StartLevelTimer(0.15, function()
      GameObjects.PktRft_A.LuaObjectScript.StartCombatState()
    end)
    timers.StartLevelTimer(0.35, function()
      GameObjects.PktRft_B.LuaObjectScript.StartCombatState()
    end)
    timers.StartLevelTimer(8, function()
      GameObjects.PktRft_A.LuaObjectScript.SpawningDone()
    end)
    timers.StartLevelTimer(10, function()
      GameObjects.PktRft_B.LuaObjectScript.SpawningDone()
    end)
  end, 2)
  enc_For260_Fight_02:OnComplete(function()
    _G.SetEncounterComplete()
    _G.CA_Arena_Enable()
    _G.LTW_Lobby_Enable()
    _G.OpenArenaDoors()
    Stop_FightRift()
    Event_Complete()
  end)
end
function FNC_For260_Fight_01()
  enc_For260_Fight_01 = EC.NewEncounter(thisLevel, "FOR260 Chisel Secret Draugr", {
    LeashZone = "LeashZone260_2"
  })
  enc_For260_Fight_01:AddWave({
    {
      spawners = "Draugr_DW_PB_STATUE",
      spawnLocators = "A1_O_Loc_1",
      useSpawnLocatorsOnly = true,
      spawnWad = "For260_ChiselDungeon",
      markerID = "PowerBodyStatue",
      maxActive = 1,
      totalSpawns = 1,
      spawnCooldown = 0
    }
  })
  enc_For260_Fight_01:SetStartZone(GameObjects.EntZn_2_Attack)
  ChiselAlertWaveZoneMonitor = monitors.CreateEntityZoneMonitor(player, thisLevel:GetGameObject("EntZn_2_Alert"))
  ChiselAlertWaveZoneMonitor:OnEnter(function()
    local secretDraugr = LD.FindSingleAIByMarker("PowerBodyStatue")
    if secretDraugr ~= nil then
      secretDraugr:TriggerMoveEvent("kLEAlert")
    end
  end)
  ChiselAlertWaveZoneMonitor:SetTriggerCountLimit(1)
end
function PocketRift_Cbt_CallBack_01()
  timers.StartLevelTimer(2, function()
    enc_For260_Fight_02:Start()
  end)
  timers.StartLevelTimer(9, function()
    GameObjects.LPktRft_StartFight.LuaObjectScript.SpawningDone()
  end)
end
function Stop_FightRift()
  GameObjects.LPktRft_StartFight.LuaObjectScript.StopCombatState()
end
function HideRift_Callback()
  GameObjects.LPktRft_StartFight.LuaObjectScript.Disable()
end
function Set_Encounter_Timer(timeRequirement, encounter)
  ec_TimeRequirement = timeRequirement
  ecTimer = StartLevelTimer(timeRequirement, function()
    EventFailed_TimeElapsed(encounter)
  end)
  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(encounter)
  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(encounter)
  encounter:Reset()
  encounter:Stop()
  ResetRift_Callback(encounter)
  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(encounter)
  GameObjects.LPktRft_StartFight.LuaObjectScript.ResetCombatState()
  _G.OpenArenaDoors()
  _G.CA_Arena_Enable()
  _G.LTW_Lobby_Enable()
end
