---------------------------
-- Notification Provider --
---------------------------
local AddOnName, nsVars = ...
local ss = nsVars.SS

local table, pairs = table, pairs
local CreateFrame, UIParent = CreateFrame, UIParent

local frame

local createFrame = function()
  -- Notification frame.
  local frm = CreateFrame("Frame", ss._f .. "Notification", UIParent)
  frm:SetWidth (400)
  frm:SetHeight(200)
  frm:SetPoint ("CENTER", 0, 0)
  
  -- Background.
  frm:SetBackdrop {
    bgFile   = "Interface/Tooltips/UI-Tooltip-Background",
    edgeFile = "Interface/Tooltips/UI-Tooltip-Border",
    tile     = true,
    tileSize = 16,
    edgeSize = 16,
    insets = {
      left   = 4,
      right  = 4,
      top    = 4,
      bottom = 4
    }
  }
  frm:SetBackdropColor(0.067, 0.067, 0.067)
  
  -- Title background.
  frm.titleBackground = frm:CreateTexture(nil, "BACKGROUND")
  frm.titleBackground:SetColorTexture(1, 1, 1, 1)
  frm.titleBackground:SetVertexColor (0.067, 0.067, 0.067, 0.5)
  frm.titleBackground:SetPoint       ("TOP", 0, -5)
  frm.titleBackground:SetWidth       (395)
  frm.titleBackground:SetHeight      (25)
  
  -- Title.
  frm.title = frm:CreateFontString(ss._f .. "NotificationTitle")
  frm.title:SetFont (ss.SharedMedia.fontChoices[3], 14)
  frm.title:SetPoint("TOP", 0, -5)
  frm.title:SetSize (400, 25)
  
  -- Content.
  frm.content = frm:CreateFontString(ss._f .. "NotificationContent")
  frm.content:SetFont    (ss.SharedMedia.fontChoices[2], 14)
  frm.content:SetPoint   ("BOTTOM", 0, 50)
  frm.content:SetSize    (350, 110)
  frm.content:SetJustifyV("TOP")
  frm.content:SetJustifyH("LEFT")
  
  -- Close button.
  frm.close = CreateFrame("Button", ss._f .. "NotificationClose", frm, "GameMenuButtonTemplate")
  frm.close:SetSize  (75, 25)
  frm.close:SetPoint ("BOTTOMRIGHT", -10, 10)
  frm.close:SetText  ("Close")
  frm.close:SetScript("OnClick", function()
    frm:Hide()
  end)
  
  return frm
end

local postNotification = function(title, content, buttonText)
  frame = frame or createFrame()
  frame.content:SetText(content or "")
  frame.title  :SetText(title or "")
  frame.close  :SetText(buttonText or "Close")
  frame:Show()
end

local mtNotification = {};


function mtNotification:Notify(title, content, buttonText)
  if title and content then
    postNotification(title, content, buttonText)
  elseif self.queue then
    local completed = {}
    
    for k, v in pairs(self.queue) do
      completed[k] = v
    end
    
    for k, v in pairs(completed) do
      table.remove(self.queue, k)
    end
  end
end

function mtNotification:Queue(title, content, buttonText)
  self.queue = self.queue or {}
  table.insert(self.queue, title, content, buttonText)
end

ss["Notification"] = setmetatable({}, { __index = mtNotification });
