-- this value keeps the display from popping up on startup from initializing the scale slider
local INITIAL_SCALE = true;
local LAST_SCALE = 0;

local L = LibStub("AceLocale-3.0"):GetLocale("MegaDamage", true);

-- ********** variables for storing previous values **********
local OLD_SOUND_ENABLE = false;
local OLD_DAMAGE_SOUND = 1;
local OLD_HEALING_SOUND = 1;
local OLD_SCALE = 10;
local OLD_OPACITY = 10;
local OLD_DAMAGE_THRESHOLD = 30;
local OLD_HEALING_THRESHOLD = 30;
local OLD_PREFIX = false;
local OLD_LIFETIME_DISPLAYED = true;
local OLD_LOAD_MESSAGE = false;
-- ***********************************************************

local CONFIG_SHOWN = false;

--========================================
-- Setting up the config frame
--========================================
function MegaDamageConfig_OnLoad(self)
    self.name = L["ADDON_TITLE"];
    self.okay = function(self) MegaDamageConfig_Close(); end;
    self.cancel = function(self) MegaDamageConfig_Cancel(); end;
    self.refresh = function(self) MegaDamageConfig_Refresh(); end;
    self.default = function(self) MegaDamageConfig_SetDefaults(); end;
    InterfaceOptions_AddCategory(self);

    MegaDamageConfigTitle:SetText(string.format(L["VERSION_TEXT"], "|cffffffffv" .. MEGA_DAMAGE_VERSION));

    -- ********** sound options **********
    MegaDamageConfig_SoundOptionsTitle:SetText(L["CONFIG_HEADING_SOUND"]);

    -- enable sound
	MegaDamageConfig_SoundOptions_EnableText:SetText(L["OPTION_ENABLESOUND"]);
	MegaDamageConfig_SoundOptions_Enable.tooltip = L["OPTION_TOOLTIP_ENABLESOUND"];

    -- damage sound select
    MegaDamageConfig_SoundOptions_DamageSoundLabel:SetText(L["OPTION_SOUND_SELECT_DAMAGE"]);
    MegaDamageConfig_SoundOptions_DamageSoundPreview:SetText(L["OPTION_SOUND_PREVIEW"]);

    -- healing sound select
    MegaDamageConfig_SoundOptions_HealingSoundLabel:SetText(L["OPTION_SOUND_SELECT_HEALING"]);
    MegaDamageConfig_SoundOptions_HealingSoundPreview:SetText(L["OPTION_SOUND_PREVIEW"]);

    -- ********** frame options **********
    MegaDamageConfig_FrameOptionsTitle:SetText(L["CONFIG_HEADING_FRAME"]);

    -- scale
	MegaDamageConfig_FrameOptions_Scale.tooltip = L["OPTION_TOOLTIP_SCALE"];

    -- opacity
	MegaDamageConfig_FrameOptions_Alpha.tooltip = L["OPTION_TOOLTIP_OPACITY"];

    -- position
    MegaDamageConfig_FrameOptions_LockText:SetText(L["OPTION_LOCK"]);
    MegaDamageConfig_FrameOptions_ResetPos:SetText(L["OPTION_RESETPOS"]);

    -- ********** other options **********
    MegaDamageConfig_OtherOptionsTitle:SetText(L["CONFIG_HEADING_OTHER"]);

    -- damage threshold
	MegaDamageConfig_OtherOptions_DamageThreshold.tooltip = L["OPTION_TOOLTIP_THRESHOLD_DAMAGE"];

    -- healing threshold
	MegaDamageConfig_OtherOptions_HealThreshold.tooltip = L["OPTION_TOOLTIP_THRESHOLD_HEALING"];

    -- accurate prefixation
	MegaDamageConfig_OtherOptions_PrefixText:SetText(L["OPTION_TERM_CORRECTION"]);
	MegaDamageConfig_OtherOptions_Prefix.tooltip = L["OPTION_TOOLTIP_TERM_CORRECTION"];

    -- loading message
	MegaDamageConfig_OtherOptions_LoadMessageText:SetText(L["OPTION_SHOW_LOAD_MESSAGE"]);
	MegaDamageConfig_OtherOptions_LoadMessage.tooltip = L["OPTION_TOOLTIP_SHOW_LOAD_MESSAGE"];

    -- ********** lifetime records **********
    MegaDamageConfig_LifetimeRecordsTitle:SetText(L["CONFIG_HEADING_RECORDS"]);

    MegaDamageConfig_LifetimeRecords_UseThresholdText:SetText(L["OPTION_LIFETIME_THRESHOLD"]);
    MegaDamageConfig_LifetimeRecords_UseThreshold.tooltip = L["OPTION_TOOLTIP_LIFETIME_THRESHOLD"];

    -- ********** set up dropdown menus **********
    UIDropDownMenu_Initialize(MegaDamageConfig_SoundOptions_DamageSoundSelect, MegaDamageConfig_InitDamageSoundSelect);
    UIDropDownMenu_SetWidth(MegaDamageConfig_SoundOptions_DamageSoundSelect, 245);

    UIDropDownMenu_Initialize(MegaDamageConfig_SoundOptions_HealingSoundSelect, MegaDamageConfig_InitHealingSoundSelect);
    UIDropDownMenu_SetWidth(MegaDamageConfig_SoundOptions_HealingSoundSelect, 245);
end

--==================================================
-- Handle when the configuration is opened
--==================================================
function MegaDamageConfig_OnOpen()
    if (CONFIG_SHOWN == true) then return; end
    MegaDamageConfig_StoreCurrentSettings();
    CONFIG_SHOWN = true;
end

--========================================
-- Sets the values of the controls to
-- reflect currently loaded settings
--========================================
function MegaDamageConfig_Refresh()
    MegaDamageConfig_OnOpen();

	MegaDamageConfig_SoundOptions_Enable:SetChecked(MEGA_DAMAGE['config']['enablesound']);
    INITIAL_SCALE = true;
	MegaDamageConfig_FrameOptions_Scale:SetValue(math.max(5, math.min(15, MEGA_DAMAGE['config']['scale'])));
    INITIAL_SCALE = false;
	MegaDamageConfig_FrameOptions_Alpha:SetValue(math.max(5, math.min(10, MEGA_DAMAGE['config']['opacity'])));
    MegaDamageConfig_FrameOptions_Lock:SetChecked(true);
	MegaDamageConfig_OtherOptions_DamageThreshold:SetValue(math.max(10, math.min(80, MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_damage'])));
	MegaDamageConfig_OtherOptions_HealThreshold:SetValue(math.max(10, math.min(80, MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_heal'])));
	MegaDamageConfig_OtherOptions_Prefix:SetChecked(MEGA_DAMAGE['config']['term_correction']);
	MegaDamageConfig_OtherOptions_LoadMessage:SetChecked(MEGA_DAMAGE['config']['show_load_message']);
    MegaDamageConfig_LifetimeRecords_UseThreshold:SetChecked(MEGA_DAMAGE['config']['lifetime_threshold']);
    MegaDamageConfig_UpdateTotalsDisplay();
    ToggleDropDownMenu(1, nil, MegaDamageConfig_SoundOptions_DamageSoundSelect, "MegaDamageConfig_SoundOptions_DamageSoundSelect", 0, 0);
    UIDropDownMenu_SetSelectedID(MegaDamageConfig_SoundOptions_DamageSoundSelect, MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_damage']);
    ToggleDropDownMenu(1, nil, MegaDamageConfig_SoundOptions_DamageSoundSelect, "MegaDamageConfig_SoundOptions_DamageSoundSelect", 0, 0);
    ToggleDropDownMenu(1, nil, MegaDamageConfig_SoundOptions_HealingSoundSelect, "MegaDamageConfig_SoundOptions_HealingSoundSelect", 0, 0);
    UIDropDownMenu_SetSelectedID(MegaDamageConfig_SoundOptions_HealingSoundSelect, MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_healing']);
    ToggleDropDownMenu(1, nil, MegaDamageConfig_SoundOptions_HealingSoundSelect, "MegaDamageConfig_SoundOptions_HealingSoundSelect", 0, 0);
end

--==================================================
-- Store current settings to restore if the user
-- presses cancel
--==================================================
function MegaDamageConfig_StoreCurrentSettings()
    OLD_SOUND_ENABLE = MEGA_DAMAGE['config']['enablesound'];
    OLD_SCALE = MEGA_DAMAGE['config']['scale'];
    OLD_OPACITY = MEGA_DAMAGE['config']['opacity'];
    OLD_PREFIX = MEGA_DAMAGE['config']['term_correction'];
    OLD_LOAD_MESSAGE = MEGA_DAMAGE['config']['show_load_message'];
    OLD_LIFETIME_DISPLAYED = MEGA_DAMAGE['config']['lifetime_threshold'];

    OLD_DAMAGE_SOUND = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_damage'];
    OLD_HEALING_SOUND = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_healing'];
    OLD_DAMAGE_THRESHOLD = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_damage'];
    OLD_HEALING_THRESHOLD = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_heal'];
end

--========================================
-- Closing the config window
--========================================
function MegaDamageConfig_Close()
    MegaDamage_LockFrame();
	CONFIG_SHOWN = false;
end

--==================================================
-- Handle clicking the Cancel button; restore
-- all settings to their previous values
--==================================================
function MegaDamageConfig_Cancel()
    MEGA_DAMAGE['config']['enablesound'] = OLD_SOUND_ENABLE;
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_damage'] = OLD_DAMAGE_SOUND;
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_healing'] = OLD_HEALING_SOUND;
    MEGA_DAMAGE['config']['scale'] = OLD_SCALE;
    MegaDamageFrame:SetScale(MEGA_DAMAGE['config']['scale'] * 0.1);
    MEGA_DAMAGE['config']['opacity'] = OLD_OPACITY;
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_damage'] = OLD_DAMAGE_THRESHOLD;
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_heal'] = OLD_HEALING_THRESHOLD;
    MEGA_DAMAGE['config']['term_correction'] = OLD_PREFIX;
    MEGA_DAMAGE['config']['show_load_message'] = OLD_LOAD_MESSAGE;
    MEGA_DAMAGE['config']['lifetime_threshold'] = OLD_LIFETIME_DISPLAYED;
    MegaDamageConfig_Close();
end



--========================================
-- Handler for checking/unchecking
-- checkbox(es)
--========================================
function MegaDamageConfig_CheckBox_OnClick(self, id)
    -- enable sound
	if (id == 1) then
		if (self:GetChecked()) then
		    MEGA_DAMAGE['config']['enablesound'] = true;
		else
		    MEGA_DAMAGE['config']['enablesound'] = false;
		end
    -- lock frame
    elseif (id == 10) then
        if (self:GetChecked()) then
            MegaDamage_LockFrame();
	    else
            MegaDamage_UnlockFrame();
        end
    -- use accurate prefix
    elseif (id == 20) then
        if (self:GetChecked()) then
            MEGA_DAMAGE['config']['term_correction'] = true;
        else
            MEGA_DAMAGE['config']['term_correction'] = false;
        end
        MegaDamageConfig_UpdateTotalsDisplay();
        MegaDamage_AddMessage(L["PREFIX_CHANGE"], 0, true, false, false, true, true);
    -- show loading message
    elseif (id == 21) then
        if (self:GetChecked()) then
            MEGA_DAMAGE['config']['show_load_message'] = true;
        else
            MEGA_DAMAGE['config']['show_load_message'] = false;
        end
    -- lifetime records use threshold
    elseif (id == 30) then
        if (self:GetChecked()) then
            MEGA_DAMAGE['config']['lifetime_threshold'] = true;
        else
            MEGA_DAMAGE['config']['lifetime_threshold'] = false;
        end
	end
end

--========================================
-- Handler for changing the scale
-- slider value
--========================================
function MegaDamageConfig_Slider_OnValueChanged(self, id)
    local newValue = self:GetValue();
    if (id == 1) then
	    MEGA_DAMAGE['config']['scale'] = newValue;
        MegaDamageFrame:SetScale(newValue * 0.1);
        if ((newValue ~= LAST_SCALE) and (not INITIAL_SCALE)) then
            MegaDamage_AddMessage(L["SCALE_CHANGE"], 0, true, false, false, true, true);
        end
        LAST_SCALE = newValue;
	    MegaDamageConfig_Slider_UpdateText(self, string.format(L["OPTION_SCALE"], (newValue * 10)));
    elseif (id == 2) then
        MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_damage'] = newValue;
        MegaDamageConfig_Slider_UpdateText(self, string.format(L["OPTION_THRESHOLD_DAMAGE"], newValue));
    elseif (id == 3) then
        MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['min_heal'] = newValue;
        MegaDamageConfig_Slider_UpdateText(self, string.format(L["OPTION_THRESHOLD_HEALING"], newValue));
    elseif (id == 4) then
	    MEGA_DAMAGE['config']['opacity'] = newValue;
	    MegaDamageConfig_Slider_UpdateText(self, string.format(L["OPTION_OPACITY"], MegaDamageConfig_GetOpacity()));
    end
end

--========================================
-- Slider text update for value changes
--========================================
function MegaDamageConfig_Slider_UpdateText(slider, text)
    _G[slider:GetName() .. "Text1"]:SetText(text);
end

--========================================
-- Handler for mousing over options
-- on the config window
--========================================
function MegaDamageConfig_Option_OnEnter(self)
	if (self.tooltip) then
        GameTooltip:SetOwner(self, "ANCHOR_NONE");
		GameTooltip:SetPoint("TOPLEFT", self:GetName(), "BOTTOMLEFT", -10, -4);
        GameTooltip:SetText(self.tooltip, 1, 1, 1);
        GameTooltip:Show();
	end
end

--========================================
-- Moving the mouse away from config
-- options
--========================================
function MegaDamageConfig_Option_OnLeave(self)
	GameTooltip:Hide();
end

--========================================
-- Update lifetime totals display
--========================================
function MegaDamageConfig_UpdateTotalsDisplay()

    if (MEGA_DAMAGE['config']['term_correction']) then
        MegaDamageConfig_LifetimeRecords_DamageTotal:SetText(string.format(L["LIFETIME_MEGA_DAMAGE"], MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_damage'] / 1000));
        MegaDamageConfig_LifetimeRecords_HealingTotal:SetText(string.format(L["LIFETIME_MEGA_HEALING"], MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_healing'] / 1000));
    else
        MegaDamageConfig_LifetimeRecords_DamageTotal:SetText(string.format(L["LIFETIME_MEGA_DAMAGE"], MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_damage']));
        MegaDamageConfig_LifetimeRecords_HealingTotal:SetText(string.format(L["LIFETIME_MEGA_HEALING"], MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_healing']));
    end

end

--========================================
-- Returns calculated opacity percentage
-- based on configuration value
--========================================
function MegaDamageConfig_GetOpacity()

    return 50 + (MEGA_DAMAGE['config']['opacity'] * 5);

end

--========================================
-- Initialize damage sound selection
-- dropdown menu
--========================================
function MegaDamageConfig_InitDamageSoundSelect()

    local info = {};

    for i = 1, table.maxn(MEGA_DAMAGE_SOUNDS), 1 do
        info.text = L["SOUND_EFFECT_" .. i];
        info.value = i;
        info.checked = nil;
        info.func = MegaDamageConfig_SelectDamageSound;
        UIDropDownMenu_AddButton(info);
    end

end

--========================================
-- Initialize healing sound selection
-- dropdown menu
--========================================
function MegaDamageConfig_InitHealingSoundSelect()

    local info = {};

    for i = 1, table.maxn(MEGA_DAMAGE_SOUNDS), 1 do
        info.text = L["SOUND_EFFECT_" .. i];
        info.value = i;
        info.checked = nil;
        info.func = MegaDamageConfig_SelectHealingSound;
        UIDropDownMenu_AddButton(info);
    end

end

--========================================
-- Selecting a damage sound
--========================================
function MegaDamageConfig_SelectDamageSound(self)
    UIDropDownMenu_SetSelectedID(MegaDamageConfig_SoundOptions_DamageSoundSelect, self:GetID());
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_damage'] = self:GetID();
end

--========================================
-- Selecting a healing sound
--========================================
function MegaDamageConfig_SelectHealingSound(self)
    UIDropDownMenu_SetSelectedID(MegaDamageConfig_SoundOptions_HealingSoundSelect, self:GetID());
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_healing'] = self:GetID();
end

--========================================
-- Handler for clicking a dropdown menu
--========================================
function MegaDamageConfig_DropDown_OnClick(self)
    ToggleDropDownMenu(1, nil, self, self:GetName(), 0, 0);
end

--========================================
-- Sound preview playback
--========================================
function MegaDamageConfig_PreviewSound(type)
    local sound_type;
    if (type == 0) then
        sound_type = "damage";
    elseif (type == 1) then
        sound_type = "healing";
    else
        return;
    end

    MegaDamage_PlaySound(MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['selected_sound_' .. sound_type], true);
end

--========================================
-- Restore global config and current
-- character's settings to defaults
--========================================
function MegaDamageConfig_SetDefaults()
    MegaDamage_ResetPosition(true);
    MegaDamage_LockFrame();

    MEGA_DAMAGE['config'] = {};
    MEGA_DAMAGE[MEGA_DAMAGE_PROFILE] = {
        ["lifetime_damage"] = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_damage'],
        ["lifetime_healing"] = MEGA_DAMAGE[MEGA_DAMAGE_PROFILE]['lifetime_healing'],
    };

    MegaDamage_LoadSettings();

    MegaDamageConfig_StoreCurrentSettings();
    MegaDamageConfig_Refresh();
end
