local LD = require("design.LevelDesignLibrary")
local thisObj, thisLevel, player, tendrilGroup, totalTendrils, currentTendrilsCut, cooldown, resetAfterCooldown, onAllTendrilsCutEvents
function OnScriptLoaded(level, obj)
  game.SubObject.Sleep(obj)
  player = game.Player.FindPlayer()
  thisObj = obj
  thisLevel = level
  currentTendrilsCut = 0
  cooldown = obj:GetLuaTableAttribute("cooldown")
  resetAfterCooldown = obj:GetLuaTableAttribute("resetAfterCooldown")
  onAllTendrilsCutEvents = LD.ExtractCallbacksForEvent(level, obj, obj:FindLuaTableAttribute("Event_AllTendrilsCut"))
  if obj:FindLuaTableAttribute("tendrilGroup") ~= nil and obj:FindLuaTableAttribute("tendrilGroup") ~= "" then
    tendrilGroup = level:GetGameObject(tostring(obj:FindLuaTableAttribute("tendrilGroup")))
    totalTendrils = #tendrilGroup.Children
    for i = 1, #tendrilGroup.Children do
      tendrilGroup.Children[i].LuaObjectScript.RegisterHitCallback(IncrementTendrilCounter)
      tendrilGroup.Children[i].LuaObjectScript.RegisterCooldownCallback(DecrementTendrilCounter)
    end
  end
end
function DecrementTendrilCounter()
  currentTendrilsCut = currentTendrilsCut - 1
end
function IncrementTendrilCounter(finalTendril)
  currentTendrilsCut = currentTendrilsCut + 1
  if currentTendrilsCut == totalTendrils then
    finalTendril.LuaObjectScript.SpawnHitFX()
    if onAllTendrilsCutEvents ~= nil and onAllTendrilsCutEvents ~= "" then
      LD.ExecuteCallbacksForEvent(thisLevel, thisObj, onAllTendrilsCutEvents, "All Tendrils Cut!")
    end
    for i = 1, #tendrilGroup.Children do
      if resetAfterCooldown == false then
        tendrilGroup.Children[i].LuaObjectScript.TendrilDestroyed()
      end
      tendrilGroup.Children[i].LuaObjectScript.AllTendrilsHit(cooldown)
      LD.CallFunctionAfterDelay(function()
        local child = tendrilGroup.Children[i]
        if child ~= nil and child.LuaObjectScript ~= nil and child.LuaObjectScript.GlobalRegrowthCooldownElapsed ~= nil then
          tendrilGroup.Children[i].LuaObjectScript.GlobalRegrowthCooldownElapsed()
        end
        currentTendrilsCut = 0
      end, cooldown)
    end
  end
end
function TEMP_HitStop(finalTendril)
  if player:PickupIsAcquired("Debuff_Hit_Stop") then
    player:PickupRelinquish("Debuff_Hit_Stop")
  end
  if player:PickupIsAcquired("Debuff_Hit_Slow") == false then
    player:PickupAcquire("Debuff_Hit_Slow")
  end
end
function GetTendrilCutCount()
  return currentTendrilsCut
end
function Reset()
  currentTendrilsCut = 0
  for i = 1, #tendrilGroup.Children do
    tendrilGroup.Children[i].LuaObjectScript.ResetState()
  end
end
function GetAllTendrilsDestroyed()
  return currentTendrilsCut == totalTendrils
end
function OnSaveCheckpoint(level, obj)
  return {currentTendrilsCut = currentTendrilsCut}
end
function OnRestoreCheckpoint(level, obj, savedInfo)
  currentTendrilsCut = savedInfo.currentTendrilsCut
end
