--------------------------------------
-- Micro Sphere Configuration Panel --
--------------------------------------
local AddOnName, nsVars = ...
local ss = nsVars.SS

local UIDropDownMenu_AddButton, UIDropDownMenu_GetText = UIDropDownMenu_AddButton, UIDropDownMenu_GetText
local pairs, CloseDropDownMenus, UIDropDownMenu_SetText = pairs, CloseDropDownMenus, UIDropDownMenu_SetText
local table, GetSpellCharges, strlower, next = table, GetSpellCharges, strlower, next
local select, string, tonumber, type, tostring = select, string, tonumber, type, tostring


local updatePreview = function()
    local text = ""

    if ss.ConfigMicroSpheres.recources and (ss.ConfigMicroSpheres.recources[1] or ss.ConfigMicroSpheres.recources.buffGroup) then
        for k,v in pairs(ss.ConfigMicroSpheres.recources.buffGroup or {ss.ConfigMicroSpheres.recources}) do
            text = text .. ((v.ssClass == "BuffData" or v.ssClass == "DebuffData") and v[1] or v.name) .. "\n"
        end
    end

    ss.ConfigMicroSpheres.previewList:SetText(text)
end

local setColorSelectColors = function(r, g, b, a)
  ss.ConfigMicroSpheres.colorDisplayText:SetVertexColor(ss:GetRGBAValues({r=r,g=g,b=b,a=a}))
end

local showColorSelect = function()
  local r, g, b, a
  
  r, g, b, a = ss.ConfigMicroSpheres.colorDisplayText:GetVertexColor()
  
  ss.ConfigMicroSpheres.colorFields:HookScript("OnColorSelect", function(self)
    setColorSelectColors(self:GetColorRGBA())
  end)
  
  ss.ConfigMicroSpheres.colorFields:SetColorRGBA(r,g,b,a)
  ss.ConfigMicroSpheres.colorFields:Show()
end

local toggleCustomResourceFields = function(show)
  if show then
    ss.ConfigMicroSpheres.newResourceEditBox:Show()
  
    if ss.ConfigMicroSpheres.resourceOptionList ~= "SpellChargeData" then
      -- Uses stacks from API.
      ss.ConfigMicroSpheres.newResourceIsStackingCheckBox:Show()
    end
  
    ss.ConfigMicroSpheres.newResourceCreateButton:Show()
    ss.ConfigMicroSpheres.colorDisplay:Show()
    showColorSelect()
    
    ss.ConfigMicroSpheres.ResourceRemoveDropDown:Hide()
    ss.ConfigMicroSpheres.ResourceRemoveDropDown.label:Hide()
    ss.ConfigMicroSpheres.ResourceDeleteDropDown:Hide()
    ss.ConfigMicroSpheres.ResourceDeleteDropDown.label:Hide()
    ss.ConfigMicroSpheres.backgroundDropDown:Hide()
    ss.ConfigMicroSpheres.backgroundDropDown.label:Hide()
    ss.ConfigMicroSpheres.previewList:Hide()
  else
    ss.ConfigMicroSpheres.newResourceEditBox:SetText("")
    ss.ConfigMicroSpheres.newResourceIsStackingCheckBox:SetChecked(false)
    ss.ConfigMicroSpheres.newResourceEditBox:Hide()
    ss.ConfigMicroSpheres.newResourceIsStackingCheckBox:Hide()
    ss.ConfigMicroSpheres.newResourceStacksEditBox:Hide()
    ss.ConfigMicroSpheres.colorDisplay:Hide()
    ss.ConfigMicroSpheres.colorFields:Hide()
    ss.ConfigMicroSpheres.newResourceCreateButton:Hide()
    
    ss.ConfigMicroSpheres.ResourceRemoveDropDown:Show()
    ss.ConfigMicroSpheres.ResourceRemoveDropDown.label:Show()
    ss.ConfigMicroSpheres.ResourceDeleteDropDown:Show()
    ss.ConfigMicroSpheres.ResourceDeleteDropDown.label:Show()
    ss.ConfigMicroSpheres.backgroundDropDown:Show()
    ss.ConfigMicroSpheres.backgroundDropDown.label:Show()
    ss.ConfigMicroSpheres.previewList:Show()
  end
end

local configureMicroSphereGroup = function(group, microResource, region)
  local regionLabel      = region and region == "secondary" and "Secondary " or ""
  local fillTextureIndex = (region and region == "secondary") and 2 or 1

  ss.ConfigMicroSpheres.widgetFrame.Title:SetText(regionLabel .. "Micro Spheres " .. group)
  ss.ConfigMicroSpheres.selectedTexture      = ss.profile.microResourceFillTextures[fillTextureIndex]
  ss.ConfigMicroSpheres.selectedTextureGroup = ss.profile.microResourceFillTextureGroups[fillTextureIndex]

  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceRemoveDropDown, "Select Resource")
  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceDeleteDropDown, "Select Resource")
  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, "Select Resource")
  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceTypeDropDown, "Select Resource Type")
  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.backgroundDropDown, ss.ConfigMicroSpheres.selectedTexture)

  ss.ConfigMicroSpheres.resourceOptionList = nil
  ss.ConfigMicroSpheres.region             = region

  local groupIndex = (group == "Group 1") and 1 or 2

  if microResource and not microResource.getMinMax and not microResource.buffGroup then
      microResource = (microResource[groupIndex] and (microResource[groupIndex].buffGroup or microResource[groupIndex].getMinMax)) and microResource[groupIndex] or {}
  elseif microResource then
      microResource = (groupIndex == 1) and microResource or {}
  end

  ss.ConfigMicroSpheres.recources = table.copy(microResource, true)
  ss.ConfigMicroSpheres.MicroSphereSaveButton:Hide()
  toggleCustomResourceFields(false)
  updatePreview()
end

local deleteCustomResource = function(name, table)
  table = table or "microResources"
  local shouldRefresh

  if ss.curClass == "druid" then
    if ss.profile[table][strlower(ss.curSpecName)] then
      for shapeshift,vals in pairs(ss.profile[table][strlower(ss.curSpecName)]) do
        for k,v in pairs(vals) do
          if v.buffGroup then
            for kk,vv in pairs(v.buffGroup) do
              if vv.name == name then
                ss.profile[table][strlower(ss.curSpecName)][shapeshift][k].buffGroup[kk] = nil
                shouldRefresh = true
              end
            end
            if shouldRefresh and next(ss.profile[table][strlower(ss.curSpecName)][shapeshift][k].buffGroup) == nil then
              ss.profile[table][strlower(ss.curSpecName)][shapeshift][k] = {}
            end
          elseif ss.profile[table][strlower(ss.curSpecName)][shapeshift][k].name == name then
            ss.profile[table][strlower(ss.curSpecName)][shapeshift][k] = {}
            shouldRefresh = true
          end
        end
      end
    end
  else
    if ss.profile[table][strlower(ss.curSpecName)] then
      for k,v in pairs(ss.profile[table][strlower(ss.curSpecName)]) do
        if v.buffGroup then
          for kk,vv in pairs(v.buffGroup) do
            if vv.name == name then
              ss.profile[table][strlower(ss.curSpecName)][k].buffGroup[kk] = nil
              shouldRefresh = true
            end
          end
          if shouldRefresh and next(ss.profile[table][strlower(ss.curSpecName)][k].buffGroup) == nil then
            ss.profile[table][strlower(ss.curSpecName)][k] = {}
          end
        elseif ss.profile[table][strlower(ss.curSpecName)][k].name == name then
          ss.profile[table][strlower(ss.curSpecName)][k] = {}
          shouldRefresh = true
        end
      end
    end
  end
  
  return shouldRefresh
end

local initMicroSphereGroupOption = function()
    local microResource = table.copy(ss.profile.microResources or {}, true)

    if ss.curClass == "druid" then
        UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, "Default" .. " - " .. "Group 2")
        UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, "Select Group")
        ss.ConfigMicroSpheres.selectedMicroGroup = {"Group 2", strlower("Default")}

        microResource = microResource[strlower(ss.curSpecName)]
        microResource = microResource and microResource[strlower("Default")] or {}
    else
        UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, "Group 2")
        UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, "Select Group")
        ss.ConfigMicroSpheres.selectedMicroGroup = {"Group 2" }

        microResource =  microResource[strlower(ss.curSpecName)] or {}
    end

    configureMicroSphereGroup("Group 2", microResource)
    CloseDropDownMenus()
end

local createCustomResource = function()
  local name = ss.ConfigMicroSpheres.newResourceEditBox:GetText()
  local r, g, b, a = ss.ConfigMicroSpheres.colorDisplayText:GetVertexColor()
  local funcName = "getMinMax"
  local stackNum = 1

  if ss.ConfigMicroSpheres.newResourceIsStackingCheckBox:GetChecked() then
    stackNum = tonumber(ss.ConfigMicroSpheres.newResourceStacksEditBox:GetText())
    funcName = "getStackingMinMax"
  end
  
  for i = 1, stackNum, 1 do
    local stackName = name .. ((i > 1) and tostring(i) or "")
  
    local new = {
      [1] = stackName,
      [2] = {r=r,g=g,b=b,a=a},
      getMinMax = funcName,
      name = name,
      ssClass = ss.ConfigMicroSpheres.resourceOptionList,
    }
  
    local index = strlower(string.gsub(stackName, "[ :'%(%),]", ""))
    ss.global.customResources[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass][index] = new
  end
  
  ss.MicroSphereData.loadCustomResources(ss.ConfigMicroSpheres.resourceOptionList)
  toggleCustomResourceFields(false)
  UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, "Select Resource")
end

ss["ConfigMicroSpheres"] = {
};

local initCreateResourcePanel = function()
  -- Add Name field.
  ss.ConfigMicroSpheres.newResourceEditBox = ss.ConfigTools.createEditBox{
    parent         = ss.ConfigMicroSpheres,
    name           = "NewResourceEditBox",
    width          = 150,
    height         = 25,
    anch           = "TOPLEFT",
    x              = 200,
    y              = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 6) - 15),
    letters        = 50,
    onEnterPressed = function(self)
      self:ClearFocus()
    end,
    onTextChanged  = function(self)
    end,
    label = {
      name = "NewResourceEditBoxLabel",
      text = "Name",
    },
  }
  
  local showLabel = function(self)
    self.label:Show()
  end
  
  local hideLabel = function(self)
    self.label:Hide()
  end
  
  ss.ConfigMicroSpheres.newResourceEditBox:HookScript("OnShow", showLabel)
  ss.ConfigMicroSpheres.newResourceEditBox:HookScript("OnHide", hideLabel)

  -- Add the show value checkbox.
  ss.ConfigMicroSpheres.newResourceIsStackingCheckBox = ss.ConfigTools.createCheckbox{
    name    = "newResourceIsStackingCheckBox",
    parent  = ss.ConfigMicroSpheres,
    anch    = "TOPLEFT",
    x       = 55,
    y       = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 7) - 15),
    text    = "Stacking",
    onClick = function(self)
      if self:GetChecked() then
        ss.ConfigMicroSpheres.newResourceStacksEditBox:Show()
      else
        ss.ConfigMicroSpheres.newResourceStacksEditBox:Hide()
      end
    end,
  }
  
  ss.ConfigMicroSpheres.newResourceStacksEditBox = ss.ConfigTools.createEditBox{
    parent         = ss.ConfigMicroSpheres,
    name           = "newResourceStacksEditBox",
    width          = 50,
    height         = 25,
    anch           = "TOPLEFT",
    x              = 200,
    y              = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 8) - 15),
    letters        = 1,
    onEnterPressed = function(self)
      self:ClearFocus()
    end,
    onTextChanged  = function(self)
      local val = self:GetText()
      if not tonumber(val) and val ~= "" then
        self:SetText("1")
      end
    end,
    OnEditFocusLost  = function(self)
      local val = self:GetText()
      if not tonumber(val) or val == "0" then
        self:SetText("1")
      end
    end,
    label = {
      name = "newResourceStacksEditBoxLabel",
      text = "Stack Limit",
    },
  }
  
  ss.ConfigMicroSpheres.newResourceStacksEditBox:HookScript("OnShow", showLabel)
  ss.ConfigMicroSpheres.newResourceStacksEditBox:HookScript("OnHide", hideLabel)
  
  -- Add the color picker
  ss.ConfigMicroSpheres.colorFields = ss.ConfigTools.createColorPicker{
    parent        = ss.ConfigMicroSpheres,
    name = "ConfigMicroSpheresColorPicker",
    anch          = "TOPLEFT",
    x             = 375,
    y              = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 5) - 15),
  }
  
  ss.ConfigMicroSpheres.colorDisplay = CreateFrame("Frame", "CustomResourceColorDisplay", ss.ConfigMicroSpheres)
  ss.ConfigMicroSpheres.colorDisplay:SetWidth(20)
  ss.ConfigMicroSpheres.colorDisplay:SetHeight(20)
  ss.ConfigMicroSpheres.colorDisplay:SetPoint("TOPLEFT", 350, (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 8) - 15))

  ss.ConfigMicroSpheres.colorDisplayText = ss.ConfigMicroSpheres.colorDisplay:CreateTexture(nil, "BACKGROUND")
  ss.ConfigMicroSpheres.colorDisplayText:SetColorTexture(1,1,1,1)
  ss.ConfigMicroSpheres.colorDisplayText:SetAllPoints(ss.ConfigMicroSpheres.colorDisplay)
  ss.ConfigMicroSpheres.colorDisplayText:SetVertexColor(ss:GetRGBAValues(ss.ClassResourceData.classColor(ss.curClass)))
  
  -- Add the create button.
  ss.ConfigMicroSpheres.newResourceCreateButton =  ss.ConfigTools.createButton{
    parent  = ss.ConfigMicroSpheres,
    name    = "newResourceCreateButton",
    anch    = "TOPLEFT",
    x       = 125,
    y       = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 10) - 15),
    text    = "Create",
    onClick = createCustomResource,
  }
  
  ss.ConfigMicroSpheres.newResourceEditBox:Hide()
  ss.ConfigMicroSpheres.newResourceEditBox.label:Hide()
  ss.ConfigMicroSpheres.newResourceIsStackingCheckBox:Hide()
  ss.ConfigMicroSpheres.newResourceStacksEditBox:Hide()
  ss.ConfigMicroSpheres.newResourceStacksEditBox.label:Hide()
  ss.ConfigMicroSpheres.colorDisplay:Hide()
  ss.ConfigMicroSpheres.colorFields:Hide()
  ss.ConfigMicroSpheres.newResourceCreateButton:Hide()
end

function ss:InitializeConfigMicroSpheresPanel()
    -- Create the config preview frame
    ss.ConfigMicroSpheres = ss.Config:AddTab("Micro Spheres", initMicroSphereGroupOption)

    ss.ConfigMicroSpheres.selectedMicroGroup = ""
    ss.ConfigMicroSpheres.recources = {}
    ss.ConfigMicroSpheres.group1    = {}
    ss.ConfigMicroSpheres.group2    = {}

    -- Add the widget container
    ss.ConfigMicroSpheres.widgetFrame = ss.ConfigTools.getWidgetContainer(ss.ConfigMicroSpheres, "ConfigMicroSpheresWidgetFrame")

    -- Add micro sphere group select dropdown
    ss.ConfigMicroSpheres.MicroSphereSettingsDropDown = ss.ConfigTools.createDropdown{
        name   = "ConfigMicroSphereSettingsDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 125,
        height = 50,
        anchor = "TOPLEFT",
        x      = ss.ConfigTools.itemPadCorner + ss.ConfigTools.leftLabelMargin,
        y      = 5 - ss.ConfigTools.itemPadCorner,
        init   = function(self, level, menuList)
            local stuff       = {}
            local microGroups = ss.MicroSphereData.getGroupList()

            if level == 1 then
                for k,v in ss.pairsByKeys(microGroups) do
                    if type(v) == "table" then
                        stuff.text     = k
                        stuff.menuList = k
                        stuff.checked  = (ss.ConfigMicroSpheres.selectedMicroGroup[2] == strlower(k)) and (not ss.ConfigMicroSpheres.region)
                        stuff.hasArrow = true
                    else
                        stuff.text    = v
                        stuff.checked = ss.ConfigMicroSpheres.selectedMicroGroup[1] == v and not ss.ConfigMicroSpheres.region
                        stuff.func    = function(self)
                            if self:GetText() ~= "Select Group" then
                                UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, self:GetText())
                                UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, "Select Group")
                                ss.ConfigMicroSpheres.selectedMicroGroup = {v}

                                local microResource = table.copy(ss.profile.microResources or {}, true)
                                microResource       =  microResource[strlower(ss.curSpecName)] or {}

                                configureMicroSphereGroup(v, microResource)

                                CloseDropDownMenus()
                            end
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            elseif level == 2 then
                for k,v in ss.pairsByKeys(microGroups[menuList]) do
                    stuff.text    = v
                    stuff.value   = k
                    stuff.checked = (ss.ConfigMicroSpheres.selectedMicroGroup[1] == v) and (ss.ConfigMicroSpheres.selectedMicroGroup[2] == strlower(menuList)) and (not ss.ConfigMicroSpheres.region)

                    stuff.func = function(self)
                        if self:GetText() ~= "Select Group" then
                            UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, menuList .. " - " .. self:GetText())
                            UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, "Select Group")
                            ss.ConfigMicroSpheres.selectedMicroGroup = {v, strlower(menuList)}

                            local microResource = table.copy(ss.profile.microResources or {}, true)
                            microResource       =  microResource[strlower(ss.curSpecName)]
                            microResource       = microResource and microResource[strlower(menuList)] or {}

                            configureMicroSphereGroup(v, microResource)
                            CloseDropDownMenus()
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            end
        end,
        label  = {
            name     = "MicroSphereSettingsLabel",
            text     = "Micro Sphere Settings",
            location = "left",
            color    = ss.ConfigTools.headerItemColor,
        },
    };

    -- Add secondary micro sphere group select dropdown
    ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown = ss.ConfigTools.createDropdown{
        name   = "ConfigSecondaryMicroSphereSettingsDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 125,
        height = 50,
        anchor = "TOPLEFT",
        x      = ss.ConfigTools.itemPadCorner + ss.ConfigTools.leftLabelMargin,
        y      = (5 - ss.ConfigTools.itemPadCorner - ss.ConfigTools.itemHeight),
        init   = function(self, level, menuList)
            local stuff       = {}
            local microGroups = ss.MicroSphereData.getGroupList("secondary")

            if level == 1 then
                for k,v in ss.pairsByKeys(microGroups) do
                    if type(v) == "table" then
                        stuff.text     = k
                        stuff.menuList = k
                        stuff.checked  = (ss.ConfigMicroSpheres.selectedMicroGroup[2] == strlower(k)) and (ss.ConfigMicroSpheres.region == "secondary")
                        stuff.hasArrow = true
                    else
                        stuff.text    = v
                        stuff.checked = (ss.ConfigMicroSpheres.selectedMicroGroup[1] == v) and (ss.ConfigMicroSpheres.region == "secondary")
                        stuff.func    = function(self)
                            if self:GetText() ~= "Select Group" then
                                UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, "Select Group")
                                UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, self:GetText())
                                ss.ConfigMicroSpheres.selectedMicroGroup = {v}

                                local microResource = table.copy(ss.profile.microResourcesSecondary or {}, true)
                                microResource       = microResource[strlower(ss.curSpecName)] or {}

                                configureMicroSphereGroup(v, microResource, "secondary")
                                CloseDropDownMenus()
                            end
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            elseif level == 2 then
                for k,v in ss.pairsByKeys(microGroups[menuList]) do
                    stuff.text    = v
                    stuff.value   = k
                    stuff.checked = (ss.ConfigMicroSpheres.selectedMicroGroup[1] == v) and (ss.ConfigMicroSpheres.selectedMicroGroup[2] == strlower(menuList)) and (ss.ConfigMicroSpheres.region == "secondary")

                    stuff.func    = function(self)
                        if self:GetText() ~= "Select Group" then
                            UIDropDownMenu_SetText(ss.ConfigMicroSpheres.MicroSphereSettingsDropDown, "Select Group")
                            UIDropDownMenu_SetText(ss.ConfigMicroSpheres.SecondaryMicroSphereSettingsDropDown, menuList .. " - " .. self:GetText())
                            ss.ConfigMicroSpheres.selectedMicroGroup = {v, strlower(menuList)}

                            local microResource = table.copy(ss.profile.microResourcesSecondary or {}, true)
                            microResource       = microResource[strlower(ss.curSpecName)]
                            microResource       = microResource and microResource[strlower(menuList)] or {}

                            configureMicroSphereGroup(v, microResource, "secondary")
                            CloseDropDownMenus()
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            end
        end,
        label = {
            name     = "SecondaryMicroSphereSettingsLabel",
            text     = "Secondary Settings",
            location = "left",
            color    = ss.ConfigTools.headerItemColor,
        },
    };

    -- Add title
    ss.ConfigMicroSpheres.widgetFrame.Title = ss.ConfigTools.createTitle("Micro Sphere Settings", ss.ConfigMicroSpheres.widgetFrame)

    -- Add resource type select dropdown
    ss.ConfigMicroSpheres.resourceGroups = {
        debuff       = "Debuff",
        buff         = "Buff",
        spellCharges = "Spell Charges",
    };

    ss.ConfigMicroSpheres.ResourceTypeDropDown = ss.ConfigTools.createDropdown{
        name   = "ResourceTypeDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 150,
        height = 50,
        anchor = "TOPLEFT",
        x      = 200,
        y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 2) - 15),
        init   = function(self, level)
            local stuff = {}

            for k,v in ss.pairsByKeys(ss.ConfigMicroSpheres.resourceGroups) do
                stuff              = {}
                stuff.text         = v
                stuff.value        = k
                stuff.notCheckable = true

                stuff.func         = function(self)
                    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceTypeDropDown, self:GetText())

                    if k == "debuff" then
                        ss.ConfigMicroSpheres.resourceOptionList = "DebuffData"
                    elseif k == "buff" then
                        ss.ConfigMicroSpheres.resourceOptionList = "BuffData"
                    elseif k == "spellCharges" then
                        ss.ConfigMicroSpheres.resourceOptionList = "SpellChargeData"
                    else
                        ss.ConfigMicroSpheres.resourceOptions = nil
                    end

                    CloseDropDownMenus()
                    toggleCustomResourceFields(false)
                    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, "Select Resource")
                end

                UIDropDownMenu_AddButton(stuff, level)
            end
        end,
        label = {
            name = "ResourceTypeLabel",
            text = "Resource Type",
        },
    };

    -- Add resource add select dropdown
    ss.ConfigMicroSpheres.ResourceAddDropDown = ss.ConfigTools.createDropdown{
        name   = "ResourceAddDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 150,
        height = 50,
        anchor = "TOPLEFT",
        x      = 200,
        y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 3) - 15),
        init   = function(self, level)
            local stuff = {}

            if ss.ConfigMicroSpheres.resourceOptionList and ss[ss.ConfigMicroSpheres.resourceOptionList] then
                for k,v in ss.pairsByKeys(ss[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass] or {}) do
                    if (ss.ConfigMicroSpheres.resourceOptionList == "SpellChargeData" and GetSpellCharges(v.name)) or ss.ConfigMicroSpheres.resourceOptionList ~= "SpellChargeData" or (v.name == "Stormstrike" and strlower(ss.curSpecName) == "enhancement") then
                        stuff              = {}
                        stuff.notCheckable = true
                        stuff.text         = (ss.ConfigMicroSpheres.resourceOptionList == "BuffData" or ss.ConfigMicroSpheres.resourceOptionList == "DebuffData") and v[1] or v.name
                        stuff.value        = k

                        stuff.func = function(self)
                            v.ssClass = v.ssClass or ss.ConfigMicroSpheres.resourceOptionList

                            if ss.ConfigMicroSpheres.resourceOptionList == "BuffData" or ss.ConfigMicroSpheres.resourceOptionList == "DebuffData" then
                                ss.ConfigMicroSpheres.recources = ss.ConfigMicroSpheres.recources.buffGroup and ss.ConfigMicroSpheres.recources or { buffGroup = {}, }

                                if table.getn(ss.ConfigMicroSpheres.recources.buffGroup) < 10 then
                                    table.insert(ss.ConfigMicroSpheres.recources.buffGroup, v)
                                end
                            else
                                ss.ConfigMicroSpheres.recources = v
                            end
  
                          updatePreview()
                          CloseDropDownMenus()
                          toggleCustomResourceFields(false)
                          UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, "Select Resource")
                          ss.ConfigMicroSpheres.MicroSphereSaveButton:Show()
                        end

                        UIDropDownMenu_AddButton(stuff, level)
                    end
                end
                
              -- Add "Custom" button.
              stuff              = {}
              stuff.notCheckable = true
              stuff.text         = "-- Custom --"
              stuff.value        = "custom"
  
              stuff.func = function(self)
                -- TODO: Toggle create resource layout.
                UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceAddDropDown, self:GetText())
                toggleCustomResourceFields(true)
              end
  
              UIDropDownMenu_AddButton(stuff, level)
            end
        end,
        label = {
            name = "ResourceAddLabel",
            text = "Add Resource",
        },
    };

    -- Add resource remove select dropdown
    ss.ConfigMicroSpheres.ResourceRemoveDropDown = ss.ConfigTools.createDropdown{
        name   = "ResourceRemoveDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 150,
        height = 50,
        anchor = "TOPLEFT",
        x      = 200,
        y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 4) - 15),
        init = function(self, level)
            local stuff = {}

            if ss.ConfigMicroSpheres.recources and (ss.ConfigMicroSpheres.recources[1] or ss.ConfigMicroSpheres.recources.buffGroup) then
                for k,v in pairs(ss.ConfigMicroSpheres.recources.buffGroup or {ss.ConfigMicroSpheres.recources}) do
                    stuff              = {}
                    stuff.notCheckable = true
                    stuff.text         = (ss.ConfigMicroSpheres.resourceOptionList == "BuffData" or ss.ConfigMicroSpheres.resourceOptionList == "DebuffData") and v[1] or v.name
                    stuff.value        = k

                    stuff.func = function(self)
                        if ss.ConfigMicroSpheres.recources.buffGroup and ss.ConfigMicroSpheres.recources.buffGroup[2] then
                            table.remove(ss.ConfigMicroSpheres.recources.buffGroup, k)
                        else
                            ss.ConfigMicroSpheres.recources = {}
                        end

                        updatePreview()
                        CloseDropDownMenus()
                        ss.ConfigMicroSpheres.MicroSphereSaveButton:Show()
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            end
        end,
        label = {
            name = "ResourceRemoveLabel",
            text = "Remove Resource",
        },
    };
  
  -- Add resource delete select dropdown
  ss.ConfigMicroSpheres.ResourceDeleteDropDown = ss.ConfigTools.createDropdown{
    name   = "ResourceDeleteDropDown",
    parent = ss.ConfigMicroSpheres,
    tAlign = "LEFT",
    width  = 150,
    height = 50,
    anchor = "TOPLEFT",
    x      = 200,
    y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 5) - 15),
    init = function(self, level)
      local stuff = {}
  
      
      if ss.ConfigMicroSpheres.resourceOptionList and ss.global.customResources[ss.ConfigMicroSpheres.resourceOptionList] then
        for k,v in pairs(ss.global.customResources[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass]) do
          stuff              = {}
          stuff.notCheckable = true
          stuff.text         = (ss.ConfigMicroSpheres.resourceOptionList == "BuffData" or ss.ConfigMicroSpheres.resourceOptionList == "DebuffData") and v[1] or v.name
          stuff.value        = k
          
          stuff.func = function(self)
            -- Remove resource if currently in use.
            local shouldRefresh = deleteCustomResource(v.name)
            shouldRefresh       = deleteCustomResource(v.name, "microResourcesSecondary") or shouldRefresh
  
            ss.global.customResources[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass][k] = nil
            if ss[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass] then
              ss[ss.ConfigMicroSpheres.resourceOptionList][ss.curClass][k] = nil
            end
  
            if shouldRefresh then
              ss.Layout:AddMicroSpheres()
              ss.Layout:AddMicroSpheres("mainResource")
            end
            
            updatePreview()
            CloseDropDownMenus()
            initMicroSphereGroupOption()
          end
          
          UIDropDownMenu_AddButton(stuff, level)
        end
      end
    end,
    label = {
      name = "ResourceDeleteLabel",
      text = "Delete Custom",
    },
  };

    -- Add Backgrounds.
    local textureNameTable   = ss.FillTextures.listAll()

    ss.ConfigMicroSpheres.backgroundDropDown = ss.ConfigTools.createDropdown{
        name   = "backgroundDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 150,
        height = 50,
        anchor = "TOPLEFT",
        x      = 200,
        y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 6) - 15),
        init   = function(self, level, menuList)
            local stuff = {}

            if level == 1 then
                for k,v in ss.pairsByKeys(textureNameTable) do
                    stuff.text     = k
                    stuff.menuList = k
                    stuff.hasArrow = true
                    stuff.checked = (ss.ConfigMicroSpheres.selectedTextureGroup == k)

                    UIDropDownMenu_AddButton(stuff, level)
                end
            elseif level == 2 then
                for k,v in ss.pairsByKeys(textureNameTable[menuList]) do
                    stuff.text    = k
                    stuff.value   = k
                    stuff.checked = (ss.ConfigMicroSpheres.selectedTexture == k)
                    stuff.func    = function(self)
                      UIDropDownMenu_SetText(ss.ConfigMicroSpheres.backgroundDropDown, self:GetText())
                      ss.ConfigMicroSpheres.selectedTexture      = self:GetText()
                      ss.ConfigMicroSpheres.selectedTextureGroup = menuList
                      ss.ConfigMicroSpheres.MicroSphereSaveButton:Show()
                      CloseDropDownMenus()
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            end
        end,
        label = {
            name = "BackgroundLabel",
            text = "Background",
        },
    };

    -- Add the list of current micro resources.
    ss.ConfigMicroSpheres.previewList = ss.ConfigTools.createLabel{
        parent   = ss.ConfigMicroSpheres,
        name     = "ss.ConfigMicroSpheresPreviewList",
        width    = 200,
        height   = 200,
        anch     = "TOP",
        x        = 0,
        y        = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 8) - 15),
        color    = ss.ConfigTools.headerItemColor,
        justifyV = "TOP",
    }
  
    initCreateResourcePanel()

    -- Add the save button.
    ss.ConfigMicroSpheres.MicroSphereSaveButton =  ss.ConfigTools.createButton{
        parent  = ss.ConfigMicroSpheres,
        name    = "MicroSphereCommitButton",
        anch    = "BOTTOMRIGHT",
        x       = -15,
        y       = 15,
        text    = "Save Changes",
        onClick = function(self)
            local index       = select(2, string.split(" ", ss.ConfigMicroSpheres.selectedMicroGroup[1]))
            local fillTexture = UIDropDownMenu_GetText(ss.ConfigMicroSpheres.backgroundDropDown)
            if ss.ConfigMicroSpheres.region and ss.ConfigMicroSpheres.region == "secondary" then
                ss.profile.microResourceFillTextures[2]      = fillTexture and fillTexture
                ss.profile.microResourceFillTextureGroups[2] = ss.ConfigMicroSpheres.selectedTextureGroup
                ss.Layout:UpdateMicroSphereTextures(ss.ConfigMicroSpheres.selectedTextureGroup, fillTexture, "mainResource")
                ss.MicroSphereData.setSecondary(ss.ConfigMicroSpheres.recources, tonumber(index), ss.ConfigMicroSpheres.selectedMicroGroup[2])
            else
                ss.profile.microResourceFillTextures[1]      = fillTexture and fillTexture
                ss.profile.microResourceFillTextureGroups[1] = ss.ConfigMicroSpheres.selectedTextureGroup
                ss.Layout:UpdateMicroSphereTextures(ss.ConfigMicroSpheres.selectedTextureGroup, fillTexture)
                ss.MicroSphereData.set(ss.ConfigMicroSpheres.recources, tonumber(index), ss.ConfigMicroSpheres.selectedMicroGroup[2])
            end
          self:Hide()
        end,
    }
end
