local timer = require("level.timer")
local holdWideShotTimer = timer.StartLevelTimer(1)
holdWideShotTimer:Stop()
local playerCreature = game.Player.FindPlayer()
local enemiesNearby, enemiesInLargeRadius
local numLiveEnemies = 0
local offscreenThreats = 0
local enemyPosition = engine.Vector.New()
local enemyFrustumPenetrate = 0
local prevThreats = 0
local beatDownCollection
local bDoingBeatdown = false
function OnScriptLoaded(level, camera)
  playerCreature = game.Player.FindPlayer()
  beatDownCollection = playerCreature:FindMoveCollection("MVC_BeatDown")
  if beatDownCollection == nil then
    return
  end
end
function OnUpdate(level, camera)
  if playerCreature == nil then
    playerCreature = game.Player.FindPlayer()
  end
  numLiveEnemies = 0
  offscreenThreats = 0
  enemiesNearby = playerCreature:FindEnemies(5)
  enemiesInLargeRadius = playerCreature:FindEnemies(30)
  bDoingBeatdown = playerCreature:IsDoingCollectionMove(beatDownCollection)
  for _, thisEnemy in ipairs(enemiesNearby) do
    if thisEnemy:IsDead() == false then
      enemyPosition = thisEnemy:GetWorldPosition()
      enemyFrustumPenetrate = game.Camera.GetViewPenetration(enemyPosition, 0, 0)
      if enemyFrustumPenetrate < 0.1 then
        offscreenThreats = offscreenThreats + 1
      end
    end
  end
  for _, thisEnemy in ipairs(enemiesInLargeRadius) do
    if thisEnemy:IsDead() == false then
      numLiveEnemies = numLiveEnemies + 1
    end
  end
  if 0 < prevThreats and offscreenThreats == 0 and holdWideShotTimer.running == false then
    print(camera.name .. ": Start Timer")
    holdWideShotTimer:Start()
  end
  if bDoingBeatdown == true then
    if numLiveEnemies == 1 then
      game.Camera.SubmitCameraByName("CBT_BeatDown_Close")
    elseif 0 < offscreenThreats then
      submitCombatWideShot(camera)
    elseif offscreenThreats == 0 and holdWideShotTimer.running == true then
      submitCombatWideShot(camera)
    end
  end
  if holdWideShotTimer.fired == true then
    print(camera.name .. ": hold timer fired (finished). Restart.")
    holdWideShotTimer:Restart()
    holdWideShotTimer:Stop()
  end
  prevThreats = offscreenThreats
end
function OnTeardown(level, camera)
end
function submitCombatWideShot(camera)
  if camera.name == "CBT_BeatDown" or camera.name == "CBT_BeatDown_Wide" then
    game.Camera.SubmitCameraByName("CBT_BeatDown_Wide")
  end
end
function OnSaveCheckpoint(level)
end
function OnRestoreCheckpoint(level, go, tab)
end
