-- ------------------------------------------------------------------------------ --
--                                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 General = TSM.MainUI.Settings:NewPackage("General")
local L = LibStub("AceLocale-3.0"):GetLocale("TradeSkillMaster") -- loads the localization table
local LibDBIcon = LibStub("LibDBIcon-1.0")
local private = { characterList = {}, guildList = {}, chatFrameList = {} }



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

function General.OnInitialize()
	TSM.MainUI.Settings.RegisterSettingPage("General Settings", "top", private.GetGeneralSettingsFrame)
end



-- ============================================================================
-- General Settings UI
-- ============================================================================

function private.GetGeneralSettingsFrame()
	wipe(private.characterList)
	wipe(private.guildList)
	wipe(private.chatFrameList)
	for character in pairs(TSMAPI.Player:GetCharacters(true)) do
		if character ~= UnitName("player") then
			tinsert(private.characterList, character)
		end
	end
	for guild in pairs(TSMAPI.Player:GetGuilds(true)) do
		tinsert(private.guildList, guild)
	end
	local chatFrameValue, defaultValue
	for i=1, NUM_CHAT_WINDOWS do
		local name = strlower(GetChatWindowInfo(i) or "")
		if DEFAULT_CHAT_FRAME == _G["ChatFrame"..i] then
			defaultValue = name
		end
		if name ~= "" then
			if name == TSM.db.global.coreOptions.chatFrame then
				chatFrameValue = name
			end
			tinsert(private.chatFrameList, name)
		end
	end
	chatFrameValue = chatFrameValue or defaultValue

	return TSMAPI_FOUR.UI.NewElement("ScrollFrame", "generalSettings")
		:SetStyle("padding", 10)
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("generalOptionsTitle", L["General Options"]))
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("minimapIcon", L["Hide minimap icon?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "minimapIconToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.coreOptions.minimapIcon, "hide")
				:SetScript("OnValueChanged", private.MinimapOnValueChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("globalOperations", L["Store operations globally?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "globalOperationsToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.coreOptions, "globalOperations")
				:SetScript("OnValueChanged", private.GlobalOperationsOnValueChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("chatTab", L["Chat tab:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Dropdown", "chatTabDropdown")
				:SetItems(private.chatFrameList, chatFrameValue)
				:SetScript("OnSelectionChanged", private.ChatTabOnSelectionChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("forgetChar", L["Forget these characters:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Dropdown", "forgetCharDropdown")
				:SetItems(private.characterList)
				:SetScript("OnSelectionChanged", private.ForgetCharacterOnSelectionChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateSettingLine("ignoreGuilds", L["Ignore these guilds:"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Dropdown", "ignoreGuildsDropdown")
				:SetMultiselect(true)
				:SetItems(private.guildList, TSM.db.factionrealm.coreOptions.ignoreGuilds)
				:SetScript("OnSelectionChanged", private.IgnoreGuildsOnSelectionChanged)
			)
		)
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("profilesTitle", L["Profiles & Account Syncing"]))
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "profile")
			:SetLayout("HORIZONTAL")
			:SetStyle("height", 24)
			:SetStyle("margin", { top = -16, bottom = 16 })
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
				:SetStyle("fontHeight", 16)
				:SetText(L["You can change the active database profile, so you can have different settings for every character."])
			)
		)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "profileList")
			:SetLayout("HORIZONTAL")
			:SetStyle("height", 24)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
				:SetStyle("fontHeight", 18)
				:SetText(L["Profiles"])
			)
		)
		:AddChildrenWithFunction(private.AddProfileRows)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "sync")
			:SetLayout("VERTICAL")
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
				:SetStyle("height", 40)
				:SetStyle("fontHeight", 18)
				:SetText(L["Account Syncing"])
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
				:SetStyle("height", 24)
				:SetStyle("margin", { top = -11, bottom = 16 })
				:SetStyle("fontHeight", 16)
				:SetText(L["TSM can sync data between multiple accounts automatically whenever you're logged into both accounts"])
			)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "accountSyncInputFrame")
			:SetLayout("HORIZONTAL")
			:SetStyle("height", 26)
			:SetStyle("margin", { bottom = 16 })
			:AddChild(TSMAPI_FOUR.UI.NewElement("Input", "syncInput")
				:SetStyle("margin", { right = 10 })
				:SetHintText(L["Enter active character name from other account"])
			)
			:AddChild(TSMAPI_FOUR.UI.NewElement("Button", "confirmBtn")
				:SetStyle("width", 100)
				:SetStyle("height", 20)
				:SetStyle("fontHeight", 16)
				:SetStyle("borderTexture", "Interface\\Addons\\TradeSkillMaster\\Media\\ButtonEdgeFrame.blp")
				:SetStyle("borderSize", 3)
				:SetText(L["CONFIRM"])
				:SetScript("OnClick", private.SyncConfirmOnClick)
			)
		)
		:AddChildrenWithFunction(private.AddSyncRows))
		:AddChild(TSM.MainUI.Settings.CreateHeadingLine("twitterTitle", L["Twitter Integration"]))
		:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "twitterDescription")
			:SetLayout("HORIZONTAL")
			:SetStyle("height", 70)
			:SetStyle("margin", { top = -16, bottom = 16 })
			:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
				:SetStyle("fontHeight", 16)
				:SetStyle("height", 40)
				:SetText(L["If you have WoW's Twitter integration set up, TSM will add a share link to its enhanced auction sale/purchase message as well as replace the URL in item tweets with a TSM link."])
			)
		)
		:AddChild(private.AddTweetEnhancement())
end

function private.AddProfileRows(frame)
	for _, profileName in ipairs(TSM.db:GetProfiles()) do
		private.AddProfileRow(frame, profileName)
	end
end

function private.AddProfileRow(frame, profileName)
	frame:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "profiles_"..profileName)
		:SetLayout("HORIZONTAL")
		:SetStyle("height", 24)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "playerName")
			:SetStyle("fontHeight", 16)
			:SetStyle("margin", { left = 5 })
			:SetText(profileName)
		)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Button", "resetBtn")
			:SetStyle("borderTexture", "Interface\\Addons\\TradeSkillMaster\\Media\\ButtonEdgeFrame.blp")
			:SetStyle("borderSize", 7)
			:SetStyle("width", 120)
			:SetContext(profileName)
			:SetText(RESET)
			:SetScript("OnClick", private.ResetProfileOnClick)
		)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Button", "deleteBtn")
			:SetStyle("borderTexture", "Interface\\Addons\\TradeSkillMaster\\Media\\ButtonEdgeFrame.blp")
			:SetStyle("borderSize", 7)
			:SetStyle("width", 120)
			:SetContext(profileName)
			:SetText(DELETE)
			:SetScript("OnClick", private.RemoveProfileOnClick)
		)
	)
end

function private.AddSyncRows(frame)
	for _, account in TSM.db:SyncAccountIterator() do
		private.AddSyncRow(frame, account)
	end
end

function private.AddSyncRow(frame, account)
	frame:AddChild(TSMAPI_FOUR.UI.NewElement("Frame", "sync_"..account)
		:SetLayout("HORIZONTAL")
		:SetStyle("height", 24)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Button", "removeBtn")
			:SetStyle("borderTexture", "Interface\\Addons\\TradeSkillMaster\\Media\\ButtonEdgeFrame.blp")
			:SetStyle("borderSize", 7)
			:SetStyle("width", 120)
			:SetContext(account)
			:SetText(REMOVE)
			:SetScript("OnClick", private.RemoveSyncOnClick)
		)
		:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "playerName")
			:SetText(account)
		)
	)
end

function private.AddTweetEnhancement()
	local twitterFrame = TSMAPI_FOUR.UI.NewElement("Frame", "twitterFrame")
		:SetLayout("VERTICAL")

	if C_Social.IsSocialEnabled() then
		twitterFrame:AddChild(TSM.MainUI.Settings.CreateSettingLine("twitter", L["Enable Tweet enhancement?"])
			:AddChild(TSMAPI_FOUR.UI.NewElement("Toggle", "twitterToggle")
				:SetStyle("width", 80)
				:SetStyle("height", 20)
				:SetBooleanToggle(TSM.db.global.coreOptions, "tsmItemTweetEnabled")
				:SetScript("OnValueChanged", TSM.MainUI.Settings.PromptToReload)
			)
		)
	else
		twitterFrame:AddChild(TSMAPI_FOUR.UI.NewElement("Text", "label")
			:SetStyle("textColor", "#c41f3b")
			:SetStyle("height", 20)
			:SetStyle("fontHeight", 18)
			:SetStyle("justifyH", "CENTER")
			:SetText(L["Twitter Integration not enabled."])
		)
	end

	return twitterFrame
end



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

function private.MinimapOnValueChanged(self, value)
	if value == YES then
		LibDBIcon:Hide("TradeSkillMaster")
	else
		LibDBIcon:Show("TradeSkillMaster")
	end
end

function private.GlobalOperationsOnValueChanged(self, value)
	StaticPopupDialogs["TSM_GLOBAL_OPERATIONS"] = StaticPopupDialogs["TSM_GLOBAL_OPERATIONS"] or {
		text = L["If you have multiple profile set up with operations, enabling this will cause all but the current profile's operations to be irreversibly lost. Are you sure you want to continue?"],
		button1 = YES,
		button2 = CANCEL,
		timeout = 0,
		hideOnEscape = true,
		OnAccept = function()
			-- we shouldn't be running the OnProfileUpdated callback while switching profiles
			TSM.Modules.ignoreProfileUpdated = true
			TSM.db.global.coreOptions.globalOperations = StaticPopupDialogs["TSM_GLOBAL_OPERATIONS"].newValue
			if TSM.db.global.coreOptions.globalOperations then
				-- move current profile to global
				TSM.db.global.userData.operations = CopyTable(TSM.db.profile.userData.operations)
				-- clear out old operations
				for profile in TSMAPI:GetTSMProfileIterator() do
					TSM.db.profile.userData.operations = nil
				end
			else
				-- move global to all profiles
				for profile in TSMAPI:GetTSMProfileIterator() do
					TSM.db.profile.userData.operations = CopyTable(TSM.db.global.userData.operations)
				end
				-- clear out old operations
				TSM.db.global.userData.operations = nil
			end
			TSM.Modules.ignoreProfileUpdated = false
			TSM.Modules.ProfileUpdated()
		end,
		OnCancel = function()
			--TODO
		end,
	}
	StaticPopupDialogs["TSM_GLOBAL_OPERATIONS"].newValue = value == YES and true or false
	TSMAPI.Util:ShowStaticPopupDialog("TSM_GLOBAL_OPERATIONS")
end

function private.ChatTabOnSelectionChanged(self, selection)
	TSM.db.global.coreOptions.chatFrame = selection
end

function private.ForgetCharacterOnSelectionChanged(self, selection)
	if not selection then return end
	TSM.db:RemoveSyncCharacter(selection)
	TSM.db.factionrealm.internalData.pendingMail[selection] = nil
	TSM.db.factionrealm.internalData.characterGuilds[selection] = nil
	TSM:Printf(L["%s removed."], selection)
	wipe(private.characterList)
	for character in pairs(TSMAPI.Player:GetCharacters(true)) do
		if character ~= UnitName("player") then
			tinsert(private.characterList, character)
		end
	end
	self:SetItems(private.characterList)
	self:Draw()
end

function private.IgnoreGuildsOnSelectionChanged(self, selection)
	wipe(TSM.db.factionrealm.coreOptions.ignoreGuilds)
	for guild, selected in pairs(selection) do
		if selected then
			TSM.db.factionrealm.coreOptions.ignoreGuilds[guild] = true
		end
	end
end

function private.ResetProfileOnClick()

end

function private.RemoveProfileOnClick()

end

function private.SyncConfirmOnClick(self)
	local newPlayer = strtrim(self:GetElement("__parent.syncInput"):GetText())
	if TSM.Sync.Connection.Establish(newPlayer) then
		TSM:Printf(L["Establishing connection to %s. Make sure that you've entered this character's name on the other account."], newPlayer)
	else
		self:GetElement("__parent.syncInput"):SetText("")
	end
end

function private.RemoveSyncOnClick(self)
	local account = self:GetContext()
	TSM.Sync.Connection.Remove(account)
	TSM:Print(L["Sync removed. Make sure you remove the sync from the other account as well."])

	-- remove this row
	local row = self:GetParentElement()
	local frame = row:GetParentElement()
	frame:RemoveChild(row)
	row:Release()
	frame:Draw()
end
