-- ------------------------------------------------------------------------------ --
--                                TradeSkillMaster                                --
--                http://www.curse.com/addons/wow/tradeskill-master               --
--                                                                                --
--             A TradeSkillMaster Addon (http://tradeskillmaster.com)             --
--    All Rights Reserved* - Detailed license information included with addon.    --
-- ------------------------------------------------------------------------------ --

local _, TSM = ...
local Mailing = TSM.MainUI.Settings:NewPackage("Mailing")
local L = LibStub("AceLocale-3.0"):GetLocale("TradeSkillMaster") -- loads the localization table
local private = { sounds = {} }
local MAIL_FRAME_TABS = { INBOX, L["TSM Groups"], L["Quick Send"], OTHER }



-- ============================================================================
-- Module Functions
-- ============================================================================

function Mailing.OnInitialize()
	TSM.MainUI.Settings.RegisterSettingPage("Inventory / Mailing", "middle", private.GetMailingSettingsFrame)
	for _, name in pairs(TSMAPI_FOUR.Sound.GetSounds()) do
		tinsert(private.sounds, name)
	end
end



-- ============================================================================
-- Mailing Settings UI
-- ============================================================================

function private.GetMailingSettingsFrame()
	return TSMAPI_FOUR.UI.NewElement("ScrollFrame", "mailingSettings")
		:SetStyle("padding", 10)
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("inventoryOptionsTitle", L["Inventory Options"]))
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("cleanBagsHeading", L["Clean bags automatically?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "cleanBagsAutoToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:AddOption(YES, true)
				:AddOption(NO)
				:SetScript("OnValueChanged", private.CleanBagsToggleChanged)
			)
		)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "cleanBagsFrame")
			:SetLayout("HORIZONTAL")
			:SetStyle("height", 26)
			:SetStyle("margin", { bottom = 16 })
			:AddChild(TSMAPI_FOUR.UI.NewElement("Checkbox", "cleanBagsCheckbox")
				:SetText(L["Character Bags"])
				:SetStyle("width", 200)
				:SetStyle("height", 20)
				:SetSettingInfo(TSM.db.profile.coreOptions, "cleanBags")
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Checkbox", "cleanBankCheckbox")
				:SetText(L["Character Bank"])
				:SetStyle("width", 200)
				:SetStyle("height", 20)
				:SetSettingInfo(TSM.db.profile.coreOptions, "cleanBank")
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Checkbox", "cleanReagentBankCheckbox")
				:SetText(L["Reagent Bank"])
				:SetStyle("width", 200)
				:SetStyle("height", 20)
				:SetSettingInfo(TSM.db.profile.coreOptions, "cleanReagentBank")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("moveDelayText", L["BankUI move delay:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Input", "moveDelayInput")
				:SetStyle("background", "#1ae2e2e2")
				:SetStyle("justifyH", "CENTER")
				:SetStyle("width", 90)
				:SetText(TSM.db.global.coreOptions.moveDelay)
				:SetScript("OnEscapePressed", private.MoveDelayOnEscapePressed)
				:SetScript("OnEnterPressed", private.MoveDelayOnEnterPressed)
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label2")
				:SetStyle("justifyV", "CENTER")
				:SetStyle("margin", { left = 20, right = 20 })
				:SetStyle("autoWidth", true)
				:SetText(L["(minimum 0 - maximum 2)"])
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("mailingOptionsTitle", L["Mailing Options"]))
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("mailingPage", L["Default mailing page:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Dropdown", "mailPageDropdown")
				:SetItems(MAIL_FRAME_TABS, MAIL_FRAME_TABS[TSM.db.global.mailingOptions.defaultPage])
				:SetScript("OnSelectionChanged", private.MailPageDropdownOnSelectionChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("mailDefault", L["Make Mailing default mail tab?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "mailDefaultToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "defaultMailTab")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("inboxChat", L["Enable inbox chat messages?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "inboxChatToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "inboxMessages")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("displayTotal", L["Display total money received?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "displayTotalToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "displayMoneyCollected")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("deleteNpc", L["Delete empty NPC mail?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "npcToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "deleteEmptyNPCMail")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("autoRecheck", L["Auto recheck mail?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "npcToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "autoCheck")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("reloadShow", L["Show 'Reload' button?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "reloadToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "showReloadBtn")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("bagSpace", L["Amount of bag space to keep free:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Input", "freeBagSpace")
				:SetStyle("background", "#1ae2e2e2")
				:SetStyle("justifyH", "CENTER")
				:SetText(TSM.db.global.mailingOptions.keepMailSpace)
				:SetScript("OnEscapePressed", private.FreeBagSpaceOnEscapePressed)
				:SetScript("OnEnterPressed", private.FreeBagSpaceOnEnterPressed)
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label2")
				:SetStyle("justifyV", "CENTER")
				:SetStyle("margin", { right = 20 })
				:SetStyle("autoWidth", true)
				:SetText(L["(minimum 0 - maximum 20)"])
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("mailSound", L["Open mail complete sound:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Dropdown", "soundDropdown")
				:SetItems(private.sounds, TSMAPI_FOUR.Sound.GetSounds()[TSM.db.global.mailingOptions.openMailSound])
				:SetScript("OnSelectionChanged", private.SoundOnSelectionChanged)
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Button", "testSound")
				:SetStyle("borderTexture", "Interface\\Addons\\TradeSkillMaster\\Media\\ButtonEdgeFrame.blp")
				:SetStyle("borderSize", 7)
				:SetStyle("width", 120)
				:SetStyle("height", 29)
				:SetStyle("margin", { left = 20 })
				:SetText("TEST")
				:SetScript("OnClick", private.TestSoundOnClick)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("sendingTitle", L["Sending Settings"]))
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("chatInfo", L["Enable TSM Mailing info in chat?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "infoToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "sendMessages")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("sendIndividual", L["Send items individually?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "individualToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.mailingOptions, "sendItemsIndividually")
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("sendDelayFrame", L["Mail send delay:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Input", "sendDelay")
				:SetStyle("background", "#1ae2e2e2")
				:SetText(TSM.db.global.mailingOptions.sendDelay)
				:SetScript("OnEscapePressed", private.SendDelayOnEscapePressed)
				:SetScript("OnEnterPressed", private.SendDelayOnEnterPressed)
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label2")
				:SetText(L["(minimum 0.1 - maximum 2)"])
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("restartDelayFrame", L["Restart delay (minutes):"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Input", "restartDelay")
				:SetStyle("background", "#1ae2e2e2")
				:SetText(TSM.db.global.mailingOptions.resendDelay)
				:SetScript("OnEscapePressed", private.RestartDelayOnEscapePressed)
				:SetScript("OnEnterPressed", private.RestartDelayOnEnterPressed)
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label2")
				:SetText(L["(minimum 0.5 - maximum 10)"])
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("deQuality", L["Mail disenchantables max quality:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "qualityToggle")
				:SetStyle("height", 20)
				:SetStyle("border", "#ffe2e2e2")
				:SetStyle("textColor", "#ffe2e2e2")
				:SetStyle("selectedBackground", "#ffe2e2e2")
				:AddOption(ITEM_QUALITY2_DESC, TSM.db.global.mailingOptions.deMaxQuality == 2)
				:AddOption(ITEM_QUALITY3_DESC, TSM.db.global.mailingOptions.deMaxQuality == 3)
				:AddOption(ITEM_QUALITY4_DESC, TSM.db.global.mailingOptions.deMaxQuality == 4)
				:SetScript("OnValueChanged", private.QualityToggleOnValueChanged)
			)
		)
end



-- ============================================================================
-- Local Script Handlers
-- ============================================================================

function private.MailPageDropdownOnSelectionChanged(self, selection)
	local selectionIndex = nil
	for i, v in ipairs(MAIL_FRAME_TABS) do
		if v == selection then
			selectionIndex = i
			break
		end
	end
	assert(selectionIndex)
	TSM.db.global.mailingOptions.defaultPage = selectionIndex
end

function private.FreeBagSpaceOnEscapePressed(self)
	self:SetText(TSM.db.global.mailingOptions.keepMailSpace)
	self:Draw()
end

function private.FreeBagSpaceOnEnterPressed(self)
	local value = tonumber(strtrim(self:GetText()))
	if value then
		value = TSMAPI_FOUR.Util.Round(value)
		TSM.db.global.mailingOptions.keepMailSpace = value
	else
		value = TSM.db.global.mailingOptions.keepMailSpace
	end
	self:SetText(value)
	self:Draw()
end

function private.SoundOnSelectionChanged(self, selection)
	local key = nil
	for k, v in pairs(TSMAPI_FOUR.Sound.GetSounds()) do
		if v == selection then
			key = k
			break
		end
	end
	assert(key)
	TSM.db.global.mailingOptions.openMailSound = key
end

function private.TestSoundOnClick(self)
	TSMAPI_FOUR.Sound.PlaySound(TSM.db.global.mailingOptions.openMailSound)
end

function private.SendDelayOnEscapePressed(self)
	self:SetText(TSM.db.global.mailingOptions.sendDelay)
	self:Draw()
end

function private.SendDelayOnEnterPressed(self)
	local value = tonumber(strtrim(self:GetText()))
	if value then
		value = TSMAPI_FOUR.Util.Round(value, 0.1)
		TSM.db.global.mailingOptions.sendDelay = value
	else
		value = TSM.db.global.mailingOptions.sendDelay
	end
	self:SetText(value)
	self:Draw()
end

function private.RestartDelayOnEscapePressed(self)
	self:SetText(TSM.db.global.mailingOptions.resendDelay)
	self:Draw()
end

function private.RestartDelayOnEnterPressed(self)
	local value = tonumber(strtrim(self:GetText()))
	if value then
		value = TSMAPI_FOUR.Util.Round(value, 0.5)
		TSM.db.global.mailingOptions.resendDelay = value
	else
		value = TSM.db.global.mailingOptions.resendDelay
	end
	self:SetText(value)
	self:Draw()
end

function private.QualityToggleOnValueChanged(self, value)
	if value == ITEM_QUALITY2_DESC then
		TSM.db.global.mailingOptions.deMaxQuality = 2
	elseif value == ITEM_QUALITY3_DESC then
		TSM.db.global.mailingOptions.deMaxQuality = 3
	elseif value == ITEM_QUALITY4_DESC then
		TSM.db.global.mailingOptions.deMaxQuality = 4
	else
		error("Unexpected value: "..tostring(value))
	end
end

function private.MoveDelayOnEscapePressed(self)
	self:SetText(TSM.db.global.coreOptions.moveDelay)
	self:Draw()
end

function private.MoveDelayOnEnterPressed(self)
	local value = tonumber(strtrim(self:GetText()))
	if value then
		TSM.db.global.coreOptions.moveDelay = min(max(value, 0), 2)
	else
		value = TSM.db.global.coreOptions.moveDelay
	end
	self:SetText(value)
	self:Draw()
end

function private.CleanBagsToggleChanged(self, value)
	local frame = self:GetElement("__parent.__parent.cleanBagsFrame")
	if value == YES then
		frame:Show()
	else
		TSM.db.profile.coreOptions.cleanBags = false
		TSM.db.profile.coreOptions.cleanBank = false
		TSM.db.profile.coreOptions.cleanReagentBank = false
		frame:GetElement("cleanBagsCheckbox"):SetChecked(false):Draw()
		frame:GetElement("cleanBankCheckbox"):SetChecked(false):Draw()
		frame:GetElement("cleanReagentBankCheckbox"):SetChecked(false):Draw()
		frame:Hide()
	end
end
