local SECTION_NAME = "|c6fffffff|rTimerLib Anchors";

local function createGUI(name)
    local optionsTable = {
        { -- section 1
            { -- column 1
                {
                    type = "text",
                    text = name,
                },
            },
        },
        { -- section 2
            { -- column 1
                {
                    title = "Locked",
                    type = "checkButton",
                    tooltipText = "If unchecked, you may change the location of the anchor by dragging any timer currently running on it.",
                    setting = "locked",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Display Names",
                    type = "checkButton",
                    tooltipText = "If checked, groups will have their name displayed at the head of the group.",
                    setting = "displayNames",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Display Icons",
                    type = "checkButton",
                    tooltipText = "If checked, groups will display a raid icon if applicable.",
                    setting = "displayIcons",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Move Name",
                    type = "checkButton",
                    tooltipText = "If checked, the group name will be moved to a more streamlined location.",
                    setting = "moveName",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Group Direction",
                    type = "dropDownSelector",
                    tooltipText = "Sets the direction new groups are added.",
                    values = {"up", "down", "left", "right"};
                    setting = "groupDirection",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Timer Direction",
                    type = "dropDownSelector",
                    tooltipText = "Sets the direction new timers are added to a group.",
                    values = {"up", "down", "left", "right"};
                    setting = "timerDirection",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Overflow Direction",
                    type = "dropDownSelector",
                    tooltipText = "Sets the direction overflow groups are added to a group.",
                    values = {"up", "down", "left", "right"};
                    setting = "overflowDirection",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Timer Sort",
                    type = "dropDownSelector",
                    tooltipText = "Sets the manner in which timers in a group are sorted.",
                    values = {"Time Added (A)", "Time Added (D)", "Time Remaining (A)", "Time Remaining (D)", "Percent Remaining (A)", "Percent Remaining(D)", "Alphabetical (A)", "Alphabetical (D)"};
                    setting = "timerSortMethod",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Group Sort",
                    type = "dropDownSelector",
                    tooltipText = "Sets the manner in which groups are sorted.",
                    values = {"Time Added (A)", "Time Added (D)", "Alphabetical (A)", "Alphabetical (D)"};
                    setting = "groupSortMethod",
                    hasToggle = name ~= "Default Anchor",
                }, 
                {
                    title = "Timer Setting",
                    type = "dropDown",
                    tooltipText = "Select the timer setting you want to apply to timers that don't have their own setting.",
                    func = function(self)
                        local setting = "defaultTimerSetting";
                        local info;
                        for timerName, settings in pairs(TimerLib:Get("timerSettings")) do
                            info = UIDropDownMenu_CreateInfo();
                            info.text = timerName;
                            info.checked = timerName == TimerLib:Get("anchorSettings", name, setting);
                            info.func = function() 
                                TimerLib:Set("anchorSettings", name, setting, timerName);
                                if self:GetParent().toggle then
                                    self:GetParent().toggle:SetChecked(true);
                                end
                                CloseDropDownMenus(); 
                            end
                            UIDropDownMenu_AddButton(info);
                        end
                    end,
                    setting = "defaultTimerSetting",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Name Text Color",
                    type = "colorSelect",
                    tooltipText = "Sets the color of the groups' name.",
                    setting = "nameTextColor",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
            },
            { -- column 2
                {
                    title = "Group Spacing",
                    type = "slider",
                    tooltipText = "Sets the amount of space between groups.",
                    minValue = 0, 
                    maxValue = 20,
                    valueStep = 1,
                    setting = "groupSpacing",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Timer Spacing",
                    type = "slider",
                    tooltipText = "Sets the amount of space between timers.",
                    minValue = 0, 
                    maxValue = 10,
                    valueStep = 1,
                    setting = "timerSpacing",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Scale",
                    type = "slider",
                    tooltipText = "Sets the scale of the anchor.",
                    minValue = .5, 
                    maxValue = 2,
                    valueStep = .1,
                    setting = "scale",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Max Num Groups",
                    type = "slider",
                    tooltipText = "Sets the maximum number of displayable groups.  Zero means no restriction.",
                    minValue = 0, 
                    maxValue = 10,
                    valueStep = 1,
                    setting = "maxNumGroups",
                    hasToggle = name ~= "Default Anchor",
                },
                {
                    title = "Overflow Point",
                    type = "slider",
                    tooltipText = "Sets the number of timers a group can have before it starts overflowing.  Overflow timers will be placed in a new group anchored relative to the original group.",
                    minValue = 0, 
                    maxValue = 10,
                    valueStep = 1,
                    setting = "overflowPoint",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "No Combat Alpha",
                    type = "slider",
                    tooltipText = "Sets the alpha of the anchor while out of combat.",
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "standardAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Combat Alpha",
                    type = "slider",
                    tooltipText = "Sets the alpha of the anchor while in combat.",
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "combatAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
                {
                    title = "Mouseover Alpha",
                    type = "slider",
                    tooltipText = "Sets the alpha of the anchor while mousing over its groups.",
                    minValue = 0, 
                    maxValue = 1,
                    valueStep = .05,
                    setting = "mouseoverAlpha",
                    hasToggle = name ~= "Default Anchor",
                    notSimple = true,
                },
            },
            { -- column 3
                {
                    title = "Preview",
                    type = "button",
                    tooltipText = "Show a preview of timers on this anchor.",
                    func = function()
                        local offset = 0;
                        for i = 1, 2 do
                            local g = "Scary Mob " .. i;
                            for j = 1, 3 do
                                TimerLib:NewTimer({duration = 20, time = GetTime() - offset, name = "Cool Timer " .. j}, g, nil, nil, nil, nil, name);
                                offset = offset + .5;
                            end
                        end
                    end,
                },
                {
                    title = "Reset Position",
                    type = "button",
                    tooltipText = "Reset the position of this anchor.",
                    func = function()
                        TimerLib:Set("anchorSettings", name, "positionX", nil);
                        TimerLib:Set("anchorSettings", name, "positionY", nil);
                    end,
                },
                "BREAK",
            },
        },
    };
    
    if not AsheylaLib:InSimpleMode() then
        local newButton;
        if name == "Default Anchor" then
            newButton = {
                title = "Make New Anchor!",
                type = "editBoxString",
                tooltipText = "Type in the name of a new anchor to be customized.",
                scripts = {
                    OnEditFocusGained = function(self) self:SetText(""); self:HighlightText() end,
                    OnEnterPressed = function(self) 
            			local text = self:GetText();
            			if not TimerLib:Get("anchorSettings", text) then
                            TimerLib:Set("anchorSettings", text, {});
                            createGUI(text);
                        end
                        GUILib:ShowPanel("TimerLib Anchors", text == "Default Anchor" and "main" or text);
                        self:ClearFocus();
            		end,
                },
            };
        elseif name ~= "DoTimer Anchor" and name ~= "Cooldowns Anchor" and name ~= "PlayerAuras Anchor" then
            newButton = {
                title = "Delete",
                type = "button",
                tooltipText = "Deletes this anchor.  If a timer is added to an anchor that doesn't exist, the anchor will be recreated.",
                func = function() 
                    local frame = StaticPopup_Show("TIMERLIBANCHOR", name)
                    frame.data = name;
                end,
            };
        end
        optionsTable[1][1][1] = {optionsTable[1][1][1], newButton};
    end
    
    local defaultFunc = function()
        TimerLib:Set("anchorSettings", name, {});
        InterfaceOptionsFrame:Hide(); GUILib:ShowPanel("TimerLib Anchors", name == "Default Anchor" and "main" or name);
    end
    
    local getFunc = function(...)
        local val = TimerLib:Get("anchorSettings", name, ...);
        local isReal = val ~= nil;
        if val == nil then
            val = TimerLib:Get("anchorSettings", "Default Anchor", ...);
        end
        return val, isReal;
    end
    
    local setFunc = function(...)
        TimerLib:Set("anchorSettings", name, ...);
    end
    
    local toggleTooltip = "If this checkbutton is unchecked, the setting does not apply and a default value will be used instead.  The default value will be found by looking at Default Anchor.";

    GUILib:SetGUIPanel(SECTION_NAME, name == "Default Anchor" and "main" or name, TimerLib, optionsTable, {default = defaultFunc, get = getFunc, set = setFunc, toggleTooltip = toggleTooltip, allSimple = true});
end

StaticPopupDialogs["TIMERLIBANCHOR"] = {
    text = "You are about to delete the anchor |cff00ff00%s|r.  Do you wish to proceed?",
    button1 = "Delete",
    button2 = "Cancel",
    OnAccept = function(self, name) 
        TimerLib:Set("anchorSettings", name, nil);
        local cats = INTERFACEOPTIONS_ADDONCATEGORIES;
        for i = 1, #cats do
            if cats[i].name == name then
                table.remove(cats, i);
                break;
            end
        end
        for i = 1, #cats do
            if cats[i].name == SECTION_NAME then
                if not (cats[i + 1] and cats[i + 1].parent == cats[i].name) then
                    cats[i].hasChildren = false;
                    cats[i].collapsed = nil;
                end
                break;
            end
        end
        InterfaceOptionsFrame:Hide(); GUILib:ShowPanel("TimerLib Anchors", "main");
    end,
    whileDead = 1,
    hideOnEscape = 1,
    timeout = 0,
}

local function createAnchorGUI()
    if AsheylaLib:InSimpleMode() then
        SECTION_NAME = "|c6fffffff|rAnchor Settings";
        createGUI("Default Anchor");
    else
        SECTION_NAME = "|c6fffffff|rTimerLib Anchors";
        createGUI("Default Anchor");
        for name in AsheylaLib:Alphabetize(TimerLib:Get("anchorSettings")) do
            if name ~= "Default Anchor" and name ~= "DoTimer Mouseover" and name ~= "Notifications Anchor" then
                createGUI(name);
            end
        end
    end
end
createAnchorGUI();
GUILib:AddGUICreationScript(createAnchorGUI);

local existing = {};
GUILib:AddProfileChangeScript(function()
    table.wipe(existing);
    local cats = INTERFACEOPTIONS_ADDONCATEGORIES;
    local parent;
    for i = #cats, 1, -1 do
        if cats[i].parent == SECTION_NAME then
            if TimerLib:Get("anchorSettings", cats[i].name) then
                table.insert(existing, cats[i].name);
                existing[cats[i].name] = true;
            else
                table.remove(cats, i);
            end
        elseif cats[i].name == SECTION_NAME then
            parent = cats[i];
        end
    end
    if #existing == 0 then
        parent.hasChildren = false;
        parent.collapsed = nil;
    end
    
    for name in AsheylaLib:Alphabetize(TimerLib:Get("anchorSettings")) do
        if name ~= "Default Anchor" and name ~= "DoTimer Mouseover" and name ~= "Notifications Anchor" and not existing[name] then
            createGUI(name);
        end
    end
end);
