--------------------------------------
-- 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 = table, GetSpellCharges, strlower
local select, string, tonumber, type = select, string, tonumber, type
local InterfaceOptionsFrame_OpenToCategory = InterfaceOptionsFrame_OpenToCategory

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" and v[1] or v.name) .. "\n"
        end
    end

    ss.ConfigMicroSpheres.previewList:SetText(text)
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 Sphere " .. group .. " Settings")
    ss.ConfigMicroSpheres.selectedTexture = ss.profile.microResourceFillTextures[fillTextureIndex]
    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.ResourceRemoveDropDown, "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)
    updatePreview()
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

ss["ConfigMicroSpheres"] = {
};

function ss:InitializeConfigMicroSpheresPanel()
    -- Create the config preview frame
    ss.ConfigMicroSpheres = ss.ConfigTools.createInterfaceOption{
        name    = "MicroSpheres",
        parent  = AddOnName,
        refresh = 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  = 400,
        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 pairs(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)
                                InterfaceOptionsFrame_OpenToCategory(AddOnName.." MicroSpheres")

                                CloseDropDownMenus()
                            end
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            elseif level == 2 then
                for k,v in pairs(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)
                            InterfaceOptionsFrame_OpenToCategory(AddOnName.." MicroSpheres")
                            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  = 400,
        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 pairs(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")
                                InterfaceOptionsFrame_OpenToCategory(AddOnName.." MicroSpheres")
                                CloseDropDownMenus()
                            end
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            elseif level == 2 then
                for k,v in pairs(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")
                            InterfaceOptionsFrame_OpenToCategory(AddOnName.." MicroSpheres")
                            CloseDropDownMenus()
                        end
                    end

                    UIDropDownMenu_AddButton(stuff, level)
                end
            end
        end,
        label = {
            name     = "SecondaryMicroSphereSettingsLabel",
            text     = "Secondary Micro Sphere 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 = {
        buff         = "Buff",
        spellCharges = "Spell Charges",
    };

    ss.ConfigMicroSpheres.ResourceTypeDropDown = ss.ConfigTools.createDropdown{
        name   = "ResourceTypeDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 400,
        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 pairs(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 == "buff" then
                        ss.ConfigMicroSpheres.resourceOptionList = "BuffData"
                    elseif k == "spellCharges" then
                        ss.ConfigMicroSpheres.resourceOptionList = "SpellChargeData"
                    else
                        ss.ConfigMicroSpheres.resourceOptions = nil
                    end

                    CloseDropDownMenus()
                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  = 400,
        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 pairs(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" 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" 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()
                        end

                        UIDropDownMenu_AddButton(stuff, level)
                    end
                end
            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  = 400,
        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         = v.ssClass == "BuffData" 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()
                    end

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

    -- Add Backgrounds.
    local textureNameTable = ss.FillTextures.list("primary")
    ss.ConfigMicroSpheres.backgroundDropDown = ss.ConfigTools.createDropdown{
        name   = "backgroundDropDown",
        parent = ss.ConfigMicroSpheres,
        tAlign = "LEFT",
        width  = 400,
        height = 50,
        anchor = "TOPLEFT",
        x      = 200,
        y      = (ss.ConfigTools.topMargin - (ss.ConfigTools.itemHeight * 5) - 15),
        init   = function(self, level)
            local stuff = {}

            for k,v in pairs(textureNameTable) do
                stuff       = {}
                stuff.text  = k
                stuff.value = k
                stuff.func  = function(self)
                    UIDropDownMenu_SetText(ss.ConfigMicroSpheres.backgroundDropDown, self:GetText())
                    ss.ConfigMicroSpheres.selectedTexture = self:GetText()
                    CloseDropDownMenus()
                end

                stuff.checked = ss.ConfigMicroSpheres.selectedTexture == k
                UIDropDownMenu_AddButton(stuff, level)
            end
        end,
        label = {
            name = "BackgroundLabel",
            text = "Background",
        },
    };


    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 * 7) - 15),
        color    = ss.ConfigTools.headerItemColor,
        justifyV = "TOP",
    }

    ss.ConfigMicroSpheres.MicroSphereSaveButton =  ss.ConfigTools.createButton{
        parent  = ss.ConfigMicroSpheres,
        name    = "MicroSphereCommitButton",
        anch    = "BOTTOMRIGHT",
        x       = -15,
        y       = 15,
        text    = "Save Changes",
        onClick = function()
            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.Layout:UpdateMicroSphereTextures(fillTexture, "mainResource")
                ss.MicroSphereData.setSecondary(ss.ConfigMicroSpheres.recources, tonumber(index), ss.ConfigMicroSpheres.selectedMicroGroup[2])
            else
                ss.profile.microResourceFillTextures[1] = fillTexture and fillTexture
                ss.Layout:UpdateMicroSphereTextures(fillTexture)
                ss.MicroSphereData.set(ss.ConfigMicroSpheres.recources, tonumber(index), ss.ConfigMicroSpheres.selectedMicroGroup[2])
            end
        end,
    }
end
