local timer = require("level.timer")
local DL = require("design.DesignerLibrary")
local isWallActive = false
local enemyCheckCooldown = 0
local shouldDetonate = false
thisLevel = nil
thisGO = nil
owner = nil
goPlayerCreature = nil
distanceToDetonation = 4
angleToDetonation = 75
function OnPreStart(level, go)
  thisLevel = level
  thisGO = go
  owner = go:GetEffectObjectCreator()
  goPlayerCreature = game.Player.FindPlayer()
  isWallActive = true
  if owner ~= nil then
    owner:CallScript("SetCoverWallObject", go)
  end
  enemyCheckCooldown = game.GetGameTime() + 2
end
function OnStart(level, go)
end
function OnUpdate(level, go)
  if goPlayerCreature ~= nil and isWallActive == true and owner ~= nil then
    shouldDetonate = false
    local distToPlayer = (go:GetWorldPosition() - goPlayerCreature:GetWorldPosition()).length
    if math.abs(DL.FrontAngle(go, goPlayerCreature)) > angleToDetonation or distToPlayer < distanceToDetonation then
      shouldDetonate = true
    end
    if enemyCheckCooldown <= game.GetGameTime() then
      enemyCheckCooldown = game.GetGameTime() + 1
      local nearbyCreatures = owner:FindFriendlies(2)
      for _, creature in ipairs(nearbyCreatures) do
        if creature ~= owner and creature:GetHitPoints() > 0 then
          shouldDetonate = true
        end
      end
    end
    if shouldDetonate then
      owner:CallScript("RequestCoverWallDetonation", go)
      owner = nil
    end
  end
end
function StartDestroyObj(obj)
  DestroyObj()
end
function DestroyObj()
  isWallActive = false
  if thisGO ~= nil then
    thisGO:Destroy()
  end
end
