--------------------------
-- Pending Task --
--------------------------
local AddOnName, nsVars = ...
local ss = nsVars.SS

local setmetatable = setmetatable
local InCombatLockdown = InCombatLockdown
local table, print, pairs, type, next = table, print, pairs, type, next

local pendingTasks = {}

local mtPendingTask = {
  completeAll = function(notify)
    -- Check for pending tasks
    if next(pendingTasks) == nil then
      return
    end
  
    local completed = {};
  
    for k,v in pairs(pendingTasks) do
      if InCombatLockdown() then
        break
      end
    
      if type(v) == "function" then
        v()
        if notify then
          print(AddOnName..": Completed pending task: " .. k)
        end
      elseif notify then
        print(AddOnName..": Could not complete pending task: " .. k)
      end
    
      table.insert(completed, k)
    end
  
    for k,v in pairs(completed) do
      pendingTasks[v] = nil
    end
  end,
  add = function(name, task)
    pendingTasks[name] = task
  
    if not InCombatLockdown() and ss.playerLoggedIn then
      ss.PendingTask.completeAll()
    elseif ss.playerLoggedIn then
      print(AddOnName..": " .. name .. " will be called once combat has ended.")
    end
  end,
  remove = function(name)
    pendingTasks[name] = nil
  end,
}

ss["PendingTask"] = setmetatable({}, { __index = mtPendingTask });
