local timer = require("level.timer")
local CL = require("camera.CameraLibrary")
local holdWideShotTimer = timer.StartLevelTimer(1)
holdWideShotTimer:Stop()
local hitBlurTimer = timer.StartLevelTimer(1.6)
hitBlurTimer:Stop()
local playerCreature = game.Player.FindPlayer()
local enemiesNearby, offscreenThreats
local kMinFrustum = 0.1
local prevThreats = 0
local bCriticalHealth = false
local bPrevFrameCritical = false
local playerHitPoints
local kCriticalHealthThreshold = 20
local originalFStop = 11
local targetFStop = 1.4
function OnScriptLoaded(level, camera)
  camera.FStop = originalFStop
end
function OnUpdate(level, camera)
  offscreenThreats = 0
  playerCreature = CL.FindPlayerSafetyCheck(playerCreature)
  enemiesNearby = playerCreature:FindEnemies(CL.kOffScreenRadius)
  offscreenThreats = CL.NumCreaturesBelowPenetration(enemiesNearby, kMinFrustum)
  if 0 < prevThreats and offscreenThreats == 0 and holdWideShotTimer.running == false then
    print(camera.name .. ": Start Timer")
    holdWideShotTimer:Start()
  end
  if 0 < offscreenThreats then
    submitCombatWideShot(camera)
  elseif offscreenThreats == 0 and holdWideShotTimer.running == true then
    submitCombatWideShot(camera)
  end
  if holdWideShotTimer.fired == true then
    print(camera.name .. ": hold timer fired.")
    holdWideShotTimer:Restart()
    holdWideShotTimer:Stop()
  end
  playerHitPoints = playerCreature:GetHitPoints()
  PlayerHealthBlur(playerHitPoints, camera)
  prevThreats = offscreenThreats
end
function OnTeardown(level, camera)
end
function submitCombatWideShot(camera)
end
function PlayerHealthBlur(playerHitPoints, camera)
  if playerHitPoints <= kCriticalHealthThreshold then
    bCriticalHealth = true
  else
    if bPrevFrameCritical == true then
      camera.FStop = originalFStop
    end
    if camera.FStop < originalFStop then
      camera.FStop = originalFStop
    end
    bCriticalHealth = false
    hitBlurTimer:Restart()
    hitBlurTimer:Stop()
    return
  end
  if bCriticalHealth == true and bPrevFrameCritical == false and hitBlurTimer.running == false and hitBlurTimer.running == false then
    hitBlurTimer:Start()
  end
  if hitBlurTimer.running == true and camera.FStop > targetFStop then
    camera.FStop = targetFStop
  elseif hitBlurTimer.fired == true and camera.FStop < originalFStop then
    camera.FStop = camera.FStop + 0.1
  end
  bPrevFrameCritical = bCriticalHealth
end
function OnSaveCheckpoint(level)
end
function OnRestoreCheckpoint(level, go, tab)
end
