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

local InCombatLockdown = InCombatLockdown
local table, pairs, type, next = table, 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
          ss.Utils:printf(ss.T["msg_task_completed"], AddOnName, v._t)
        end
      elseif notify and v._t then
        ss.Utils:printf(ss.T["msg_task_failed"], AddOnName, 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
      ss.Utils:printf(ss.T["msg_will_be_called"], AddOnName, text)
    end
  end,
  remove = function(name)
    pendingTasks[name] = nil
  end,
}

ss.Utils.addModule("PendingTask", mtPendingTask)
