--------------------------
-- 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._f) == "function" then
        v._f()
        if notify and v._t then
          print(AddOnName..": Completed task: " .. v._t)
        end
      elseif notify and v._t then
        print(AddOnName..": Could not complete task: " .. v._t)
      end
    
      table.insert(completed, k)
    end
  
    for k,v in pairs(completed) do
      pendingTasks[v] = nil
    end
  end,
  add = function(name, task, text)
    pendingTasks[name] = {
      _f = task,
      _t = text,
    }
  
    if not InCombatLockdown() and ss.playerLoggedIn then
      ss.PendingTask.completeAll()
    elseif ss.playerLoggedIn and text then
      print(AddOnName..": " .. text .. " will be called once combat has ended.")
    end
  end,
  remove = function(name)
    pendingTasks[name] = nil
  end,
}

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