-- Copyright (C) 2010 Tyson Brown
-- 
-- This file is part QuestHelper2, an AddOn for World of Warcraft.
-- 
-- QuestHelper2 is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- 
-- QuestHelper2 is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
-- 
-- You should have received a copy of the GNU General Public License
-- along with QuestHelper2. If not, see <http://www.gnu.org/licenses/>.

if LibDebug then LibDebug() end
local shared = select(2, ...)

-- This file provides a function to hold on to an object for
-- some amount of time, for no other reason than to prevent
-- the garbage collector from reclaiming it.

local object_expire_time = {}
local object_list = {}

local function cmp(a, b)
  return object_expire_time[a] < object_expire_time[b]
end

local remove = table.remove
local insert, erase = shared.sortedInserter(object_list, cmp), shared.sortedRemover(object_list, cmp)

local function expireNextObject()
  object_expire_time[remove(object_list, 1)] = nil
  
  local next_to_expire = object_list[1]
  
  if next_to_expire then
    return object_expire_time[next_to_expire] - GetTime()
  end
end

function shared.delayCollection(object, delay)
  delay = tonumber(delay) or 150
  local expire_time = GetTime() + delay
  
  local old_expire_time = object_expire_time[object]
  
  local need_reschedule = false
  
  if old_expire_time then
    if old_expire_time >= expire_time then
      -- No change required.
      return
    end
    
    if 1 == erase(object) then
      need_reschedule = true
    end
  end
  
  object_expire_time[object] = expire_time
  
  if 1 == insert(object) then
    need_reschedule = true
  end
  
  if need_reschedule then
    shared.cancelDelayed(expireNextObject)
    shared.onDelay(delay, expireNextObject)
  end
end
