--=============================================
---
--- GoldCounter (Core.lua) by Hexiatröhm
---
--=============================================

local format  = string.format
local gsub    = string.gsub
local floor   = math.floor
local abs     = math.abs
local sub	  = string.sub
local find    = string.find
local lower   = string.lower
local len 	  = string.len
local split   = strsplit

--- Slash Commands
SlashCmdList["GC"] = function(msg, editBox)

	if msg then msg = lower( msg ) end
	
	if msg == "options" then
		GoldCounterOptionsPanel:Show()		
		return
	end

	if msg == "lastlogin" then
		local LastLoginDateFormat = GC_TranslateDate( GC_LastLoginDate ) --- ToString with delimiters
		local LastLogoutDateFormat = GC_TranslateDate( GC_LastLogoutDate ) --- ToString with delimiters
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r ".."|cff00FFFF"..GC_Locale_Text.CHAT_LASTLOGGED.."|r |cff90EE90"..LastLoginDateFormat..
		" "..GC_LastLoginTime.."|r" )
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r ".."|cff00FFFF"..GC_Locale_Text.CHAT_LASTLOGOUT.."|r |cff90EE90"..LastLogoutDateFormat..
		" "..GC_LastLogoutTime.."|r" )
		return
	end

	if msg == "uiv" then

	local BuildInfo = select(4, GetBuildInfo())
	local ProjectInfo = WOW_PROJECT_ID

		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00UI Version:|r "..BuildInfo )
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00Project ID:|r "..ProjectInfo )
		return
	end
	
	if msg == "resetdaily" then
		GC_MyDailyData.Instance_MoneyLoot = 0
		GC_MyDailyData.Money_Loot = 0
		GC_MyDailyData.Merchant_Money = 0
		GC_MyDailyData.Auctioneer = 0
		GC_MyDailyData.MailBoxIncome = 0
		GC_MyDailyData.QuestXP = 0
		GC_MyDailyData.Merchant_Transmo = 0
		GC_MyDailyData.TaxiCost = 0
		GC_MyDailyData.Craftsmanship = 0
	return
	end

	if msg == "beacon" then
	
		if GC_Beacon then
			GC_Beacon = false
			print("|cffffff00GoldCounter|r ".."Beacon OFF")
		else GC_Beacon = true
			print("|cffffff00GoldCounter|r ".."Beacon ON")
		end
	return
	end

	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r version "..GC_Version.." by Hexiatröhm" )
	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00     /gc options|r   "..GC_Locale_Text.CHAT_SHOWOPTIONS )
	DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00     /gc lastlogin|r   "..GC_Locale_Text.CHAT_LASTLOGGED )
	
end

--============================================================================================================================================================
function GC_PLAYER_MONEY()

	local OneTimeMoneyLoot = 0
	local _, instanceType = IsInInstance()

	GC_CurrentFunds = GetMoney()
	OneTimeMoneyLoot = GC_CurrentFunds - GC_PreviousMoney --- Remember last income
	GC_PreviousMoney = GC_CurrentFunds

	if OneTimeMoneyLoot == 0 then return end

	------------------------
	--- Flash Icons --- Will process if My_GC_Settings_Local.IconsFlash == true
	--- Data = if true = Positive Lightgold Color or false = Negative Red Color
	local function FlashIcons()
		if (OneTimeMoneyLoot < 0) then
			FlashCoinIcons( false )
		else
			FlashCoinIcons( true )
		end
	end
	------------------------

		------------------------
		--- Monitor Bank Transaction - Re-adding the fund if no monitoring
		if ( GC_Events_Data.BankFrame_Open or GC_Events_Data.GuildBankFrame_Open ) and not My_GC_Settings_Local.CheckBank then

			GC_LoginMoneyInit = GC_LoginMoneyInit + OneTimeMoneyLoot
		end
		------------------------

		--- Get last money modification
		MySavedMoney = ( GC_CurrentFunds - GC_LoginMoneyInit )
		GoldCounter_Update()
		GoldCounterCharPanel_Build() -- Update Lines Panel and Total money

		-----------------------------------------
		--- Events stored in separate vars ---
		-----------------------------------------

		------------------------
		--- Get Taxi cost
		if UnitOnTaxi("player") then
			GC_MyDailyData.TaxiCost = GC_MyDailyData.TaxiCost + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Vendor trade result
		if GC_Events_Data.IsMercOpen then 
			GC_MyDailyData.Merchant_Money = GC_MyDailyData.Merchant_Money + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Auctioneer trade result
		if GC_Events_Data.Auctioneer_Open then 
			GC_MyDailyData.Auctioneer = GC_MyDailyData.Auctioneer + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Transmo trade result
		if GC_Events_Data.TransmoMerc_Open then 
			GC_MyDailyData.Merchant_Transmo = GC_MyDailyData.Merchant_Transmo + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Mail money
		if GC_Events_Data.MailBox_Open then
			GC_MyDailyData.MailBoxIncome = GC_MyDailyData.MailBoxIncome + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Looted Money
		if GC_Events_Data.isLootOpenHasMoney and instanceType == "none" then
		
			GC_MyDailyData.Money_Loot = GC_MyDailyData.Money_Loot + OneTimeMoneyLoot
			GC_Events_Data.isLootOpenHasMoney = false
			FlashIcons()
			return
		end 
		------------------------

		------------------------
		--- Professions frames (Profession and CustomOrder)
		if GC_Events_Data.Profession_Open then
			GC_MyDailyData.Craftsmanship = GC_MyDailyData.Craftsmanship + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

		------------------------
		--- Get Instance Money
		if instanceType ~= "none" and instanceType ~= "neighborhood" then
			GC_MyDailyData.Instance_MoneyLoot = GC_MyDailyData.Instance_MoneyLoot + OneTimeMoneyLoot
			FlashIcons()
			return
		end
		------------------------

end 

function GoldCounter_Reset( AutoReset )

	local Data1, Flag = "", false
	local NewDateNum = tonumber( date("%y%m%d") )
	local ChangeDate = false
	local CurrentDateStr = tostring(GC_CurrentDate)
	local Date_STR_FORMAT = CurrentDateStr:sub(1,2) .. "/" .. CurrentDateStr:sub(3,4) .. "/" .. CurrentDateStr:sub(5,6)

	GC_MyDailyData.DailyCount = GC_MyDailyData.DailyCount + MySavedMoney --- Counting difference + actions

	if NewDateNum > GC_CurrentDate then ChangeDate = true end

-------------------------------
local function SetDataToTable()

	if     ( GC_MyDailyData.DailyCount < 0 ) then MySavedMoneyHistory[1].sign = "-"
	elseif ( GC_MyDailyData.DailyCount > 0 ) then MySavedMoneyHistory[1].sign = "+"
	else MySavedMoneyHistory[1].sign = " "
	end

	MySavedMoneyHistory[1].amount = abs( GC_MyDailyData.DailyCount )

	if AutoReset then
		MySavedMoneyHistory[1].date = Date_STR_FORMAT.." |cff909090(Auto)|r"
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.CHAT_COUNT_RESET_AUTO )
	else
		MySavedMoneyHistory[1].date = Date_STR_FORMAT
		DEFAULT_CHAT_FRAME:AddMessage( "|cffffff00GoldCounter|r "..GC_Locale_Text.CHAT_COUNT_RESET )
	end

end
-------------------------------

	Data1  = MySavedMoneyHistory[1].date
	Flag   = find( Data1, Date_STR_FORMAT, 1, true ) --- Search for current date in first record

			-- if Dates are not matching and max record > 1 and one record then Shift table
			-- Keeping current date even if ChangeDate
			if not Flag and My_GC_Settings_Local.MaxHistoryRec > 1 and Data1 ~= "*" then

					for i = My_GC_Settings_Local.MaxHistoryRec - 1, 1, -1 do
						MySavedMoneyHistory[i+1].date   = MySavedMoneyHistory[i].date
						MySavedMoneyHistory[i+1].amount = MySavedMoneyHistory[i].amount
						MySavedMoneyHistory[i+1].sign   = MySavedMoneyHistory[i].sign
					end
			end

	SetDataToTable()

	MySavedMoney = 0
	GoldCounter_Update()
	GoldCounterCharPanel_Build() -- Update Lines Panel and Total money

	GoldCounter_SetHistoryList() -- Update tooltip

	GC_CurrentFunds 	= GetMoney() -- Store current funds
	GC_LoginMoneyInit	= GC_CurrentFunds
	GC_PreviousMoney 	= GC_CurrentFunds

	-------------------------------------------------
	--- if new day reset basic values
	-------------------------------------------------
	if ChangeDate then
		GC_MyDailyData.DailyCount = 0
		GC_MyDailyData.QuestXP = 0
		GC_MyDailyData.Instance_MoneyLoot = 0
		GC_MyDailyData.Money_Loot = 0
		GC_MyDailyData.Merchant_Money = 0
		GC_MyDailyData.Auctioneer = 0
		GC_MyDailyData.MailBoxIncome = 0
		GC_MyDailyData.Merchant_Transmo = 0
		GC_MyDailyData.TaxiCost = 0
		GC_MyDailyData.Craftsmanship = 0
		
		GC_CurrentDate = NewDateNum
		My_GC_Settings_Local.LastResetDate = NewDateNum
	end
	-------------------------------------------------

	PlaySound( SOUNDKIT.IG_BACKPACK_COIN_SELECT )
end

function GC_reformatInt( Value )

---  return tostring( Value ):reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")

	local NumValue = tonumber( Value ) or 0
	
	if abs( NumValue ) < 1000 then return tostring(Value)
	end

	local NewValue = tostring( Value ):reverse():gsub("%d%d%d", "%1,"):reverse():gsub("^,", "")

	NewValue = gsub( NewValue, ",", My_GC_Settings_Local.Thousand_Delimiter )

  return NewValue

end

function GoldCounter_Update()

		local AbsMoney = abs( MySavedMoney ) or 0
		
		local gold = floor(AbsMoney / 10000)
		local silver = floor((AbsMoney % 10000) / 100)
		local copper = AbsMoney % 100

		GC_MyMoney.Gold 	= tostring( gold ) or "0"
		GC_MyMoney.Silver	= format( "%02d", silver or 0 )
		GC_MyMoney.Copper	= format( "%02d", copper or 0 )


		local FormattedGold = GC_reformatInt( GC_MyMoney.Gold )

				if MySavedMoney < 0 then

					GC_MyMoney.Sign = "-"
					GC_MyMoney.Color = GC_MyMoney.NegColor

				elseif MySavedMoney > 0 then

					GC_MyMoney.Sign = "+"
					GC_MyMoney.Color = GC_MyMoney.PosColor

				else

					GC_MyMoney.Sign = " "
					GC_MyMoney.Color = GC_MyMoney.NoColor

				end

		GC_ShowCoppers:SetText( GC_MyMoney.Color..GC_MyMoney.Copper.."|r" )
		GC_ShowSilvers:SetText( GC_MyMoney.Color..GC_MyMoney.Silver.."|r" )
		GC_ShowGolds:SetText( GC_MyMoney.Color..GC_MyMoney.Sign..FormattedGold.."|r" )

		if MySavedMoney == 0 then
			GC_ResetButton:Disable()
		else
			GC_ResetButton:Enable()
		end
end

function GC_PlaySFX( Index )

	if ( Index == 1 ) then

		PlaySoundFile( "Interface\\AddOns\\GoldCounter\\SFX\\UI_VoidStorage_Redo.ogg", "SFX" )

	elseif ( Index == 2 ) then

		PlaySoundFile( "Interface\\AddOns\\GoldCounter\\SFX\\UI_VoidStorage_Undo.ogg", "SFX" )

	elseif ( Index == 3 ) then

		PlaySoundFile( "Interface\\AddOns\\GoldCounter\\SFX\\UI_EtherealWindow_Open.ogg", "SFX" )
	end
end

function GC_MinViewShowAllSetTooltip()

		local _, frameY = GoldCounter_MainFrame:GetCenter()
		local _, screenY = UIParent:GetCenter()
		local AnchorPoint = ""
	
		if frameY > screenY then
			AnchorPoint = "ANCHOR_BOTTOM"
		else
			AnchorPoint = "ANCHOR_TOP"
		end

		GoldCounter_Custom_Tooltip:SetOwner( _G["GoldCounter_MainFrame"], AnchorPoint, 30, 0 )
		GoldCounter_Custom_Tooltip:ClearLines()

		local fullViewStr = GC_MoneyCoinsTextures( nil, MySavedMoney, false )

		GoldCounter_Custom_TooltipTextLeft1:SetFontObject( GameTooltipTextSmall )
		GoldCounter_Custom_Tooltip:AddLine( fullViewStr )

end

--- Minimap Button Functions
function GC_MiniMapButton_OnClick( frame, button )

	if button == "LeftButton" then

		if not GC_ToggleSwitch then

			GC_ToggleSwitch = true
			GoldCounter_MainFrame:Hide()
			PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF )

			StopLoop1() --- Stop All Anim
			StopLoop2()

		else

			GC_ToggleSwitch = false
			GoldCounter_MainFrame:Show()
			PlaySound( SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON )

			GC_ResetFrame()

			--- Check if Resting or Fighting and start Animation
			GC_CheckResting()
			GC_CheckFighting()
		end

	elseif button == "RightButton" then

		if GoldCounterOptionsPanel:IsShown() then

			GoldCounterOptionsPanel:Hide()
		else

			GoldCounterOptionsPanel:Show()

		end

	elseif button == "MiddleButton" then

		if MySavedMoney ~= 0 then GoldCounter_Reset() end

	end
end

function GC_MiniMapButton_OnEnter( frame )

		local fText

		--- Coded for Vanilla compatibility
		GC_MinimapButtonTooltip:SetOwner( frame, "ANCHOR_TOPRIGHT")
		GC_MinimapButtonTooltip:SetPoint("TOPLEFT", frame, "BOTTOMRIGHT")
		GC_MinimapButtonTooltip:ClearLines()

		GC_MinimapButtonTooltipTextLeft1:SetFontObject( Fancy12Font )
		GC_MinimapButtonTooltip:AddLine("GoldCounter v"..GC_Version, 1, 1, 1, false )

		fText = "|cffffff00"..GC_Locale_Text.ICONTOOLTIP_LEFTCLICK..":|r "..GC_Locale_Text.ICONTOOLTIP_TEXT1
		GC_MinimapButtonTooltipTextLeft2:SetFontObject( GameFontWhiteTiny )
		GC_MinimapButtonTooltip:AddLine(fText, 1, 1, 1, false )
		--- Icon Left Click - Retail
		if GC_WOW_isRetail == true then
			GC_MinimapButtonTooltip:AddAtlas( "newplayertutorial-icon-mouse-leftbutton",

			{ width = 12, height = 16, margin = { left = 0, right = 3, top = 0, bottom = 0 } } )
		end

		fText = "|cffffff00"..GC_Locale_Text.ICONTOOLTIP_RIGHTCLICK..":|r "..GC_Locale_Text.ICONTOOLTIP_TEXT2
		GC_MinimapButtonTooltipTextLeft3:SetFontObject( GameFontWhiteTiny )
		GC_MinimapButtonTooltip:AddLine(fText, 1, 1, 1, false )
		--- Icon Right Click - Retail
		if GC_WOW_isRetail == true then
			GC_MinimapButtonTooltip:AddAtlas( "newplayertutorial-icon-mouse-rightbutton",
			{ width = 12, height = 16, margin = { left = 0, right = 3, top = 0, bottom = 0 } } )
		end

		fText = "|cffffff00"..GC_Locale_Text.ICONTOOLTIP_MIDDLECLICK..":|r "..GC_Locale_Text.ICONTOOLTIP_TEXT3
		GC_MinimapButtonTooltipTextLeft4:SetFontObject( GameFontWhiteTiny )
		GC_MinimapButtonTooltip:AddLine( fText, 1, 1, 1, false )
		--- Icon Middle Click - Retail
		if GC_WOW_isRetail == true then
		GC_MinimapButtonTooltip:AddAtlas( "newplayertutorial-icon-mouse-middlebutton",
		{ width = 12, height = 16, margin = { left = 0, right = 3, top = 0, bottom = 0 } } )
		end

		--- Incomes texts
		local DonjonMoney = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Instance_MoneyLoot, false)
		local LootMoney = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Money_Loot, false)
		local MerchantMoney = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Merchant_Money, false)
		local Auctioneer = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Auctioneer, false )
		local MailInbox = GC_MoneyCoinsTextures( nil, GC_MyDailyData.MailBoxIncome, false )
		local TaxiCost = GC_MoneyCoinsTextures( nil, GC_MyDailyData.TaxiCost, false )
		local MerchantTransmo = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Merchant_Transmo, false )
		local Craftsmanship = GC_MoneyCoinsTextures( nil, GC_MyDailyData.Craftsmanship, false )

		GC_MinimapButtonTooltip:AddLine( " ", 1, 1, 1, false )

		GC_MinimapButtonTooltipTextLeft6:SetFontObject( Fancy12Font )
		GC_MinimapButtonTooltip:AddLine( GC_Locale_Text.PLAYERCARD_INCOMES, 0, 0.4, 1, false )

		GC_MinimapButtonTooltipTextLeft7:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight7:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_DUNGEON, DonjonMoney, nil, nil, nil, false )

		GC_MinimapButtonTooltipTextLeft8:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight8:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_MONEYLOOT, LootMoney, nil, nil, nil, false )

		GC_MinimapButtonTooltipTextLeft9:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight9:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_TRADER, MerchantMoney, nil, nil, nil, false )

		GC_MinimapButtonTooltipTextLeft10:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight10:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_AUCTIONEER, Auctioneer, nil, nil, nil, false )

		GC_MinimapButtonTooltipTextLeft11:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight11:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_MAILBOX, MailInbox, nil, nil, nil, false )

		GC_MinimapButtonTooltipTextLeft12:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltipTextRight12:SetFontObject( FriendsFont_Small )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_TAXICOST, TaxiCost, nil, nil, nil, false )

		local TooltipIndex = 12

		if GC_WOW_isRetail then
		TooltipIndex = TooltipIndex + 1
		_G["GC_MinimapButtonTooltipTextLeft"..TooltipIndex]:SetFontObject( FriendsFont_Small )
		_G["GC_MinimapButtonTooltipTextRight"..TooltipIndex]:SetFontObject( FriendsFont_Small )
			GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_CRAFT, Craftsmanship, nil, nil, nil, false )
		end

		if GC_WOW_isRetail or GC_WOW_isPandaria then
		TooltipIndex = TooltipIndex + 1
		_G["GC_MinimapButtonTooltipTextLeft"..TooltipIndex]:SetFontObject( FriendsFont_Small )
		_G["GC_MinimapButtonTooltipTextRight"..TooltipIndex]:SetFontObject( FriendsFont_Small )
			GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.PLAYER_INCOMES_TRANSMO, MerchantTransmo, nil, nil, nil, false )
		end
		
		TooltipIndex = TooltipIndex + 1
		GC_MinimapButtonTooltip:AddLine( " " )

		GC_Total_Tooltip = GC_MyDailyData.Instance_MoneyLoot + GC_MyDailyData.Money_Loot + GC_MyDailyData.Merchant_Money + GC_MyDailyData.Auctioneer
		+ GC_MyDailyData.MailBoxIncome + GC_MyDailyData.TaxiCost + GC_MyDailyData.Merchant_Transmo + GC_MyDailyData.Craftsmanship

		TooltipIndex = TooltipIndex + 1
		local TooltipTotal = GC_MoneyCoinsTextures( nil, GC_Total_Tooltip, false )
		GC_MinimapButtonTooltip:AddDoubleLine( GC_Locale_Text.TOOLTIP_INFOS_TOTAL, TooltipTotal, 1, 1, 1, false )
		
		GC_MinimapButtonTooltip:Show()
end

function GC_ResetDefault()

	local LastResetDate	= My_GC_Settings_Local.LastResetDate

	--- Addon Settings
	My_GC_Settings_Local = { }
	My_GC_Settings_Local.LastResetDate 	= LastResetDate

	My_GC_Settings_Local.LastLoginDate = GC_LastLoginDate
	My_GC_Settings_Local.LastLoginTime = GC_LastLoginTime
	My_GC_Settings_Local.LastLogoutDate = GC_LastLogoutDate
	My_GC_Settings_Local.LastLogoutTime = GC_LastLogoutTime

	--- Minimap button
	GC_Icon_DB.profile.minimap = { hide = false }
	GC_Icon_DB.profile.minimap.minimapPos = nil
	GC_Icon:Refresh("GOLDCOUNTER", GC_Icon_DB.profile.minimap)

	--- Reset Position
	GoldCounter_MainFrame:ClearAllPoints()
	GoldCounter_MainFrame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
	GoldCounter_MainFrame:SetUserPlaced(true)

	--- Reset Counter and history
	GC_MyDailyData = {} --- Reset calling GC_SetAddonOptions()
	GC_SetAddonOptions()

	if MySavedMoney ~= 0 then GoldCounter_Reset( true ) end
	GC_ClearHistory()

	--- DropDown Texts
	GC_FontDropDownList_OnClick()
	GC_ThouSeparator_DropDownList_OnClick( nil, My_GC_Settings_Local.Thousand_Delimiter )
	GC_DateFormat_DropDownList_OnClick( nil, My_GC_Settings_Local.UserDateFormat )

	-------------------		
	--- Option 1 - Erase Database
	-------------------		
	if GC_Reset_EraseDB_Checked then
		GC_ClearCharDB()	
	end
	-------------------		

	-------------------		
	--- Option 2 - Reset Global Profiles
	-------------------		
	if GC_Reset_EraseAllProfiles_Checked then
		My_GC_Profile = { }	
	end
	-------------------		

	GC_PlaySFX( 2 )
end

--------------------------------------------------------
--- Convert Money number to String with textures
--------------------------------------------------------

function GC_MoneyCoinsTextures( NumSign, amount, Raw )

	if not amount then return nil end

	amount = tonumber( amount ) or 0 --- Make sure amount is a number

	local StringColor = ""
	
	--- Default number's sign and color
	if not NumSign then
	
			NumSign = " "
			StringColor = GC_MyMoney.NoColor
		
	elseif NumSign == "+" then

			StringColor = GC_MyMoney.PosColor
	
	elseif NumSign == "-" then

			StringColor = GC_MyMoney.NegColor
	end
		

	if amount ~= 0 then 
	
			if amount > 0 and NumSign == " " then

					NumSign  = "+"
					StringColor = GC_MyMoney.PosColor

			elseif amount < 0 and NumSign == " " then

					NumSign  = "-"
					StringColor = GC_MyMoney.NegColor
			end

	else

		if Raw then return "0|TInterface\\MoneyFrame\\UI-CopperIcon:14:14:2:0|t" end
			
	end	


	-------------------------
	--- Format Money String
	-------------------------

	amount = abs(amount) --- In case it's negative "-"

		local TextureString = ""
		local CoinsString = ""

		local CurrentGold = floor( amount / 1e4 )
		local CurrentSilver = floor( amount / 100 ) % 100
		local CurrentCopper = amount % 100

	if amount ~= 0 then 

		--- Add Thousand Delimiter
		local _Gold = GC_reformatInt( CurrentGold )

		if CurrentGold > 0 then
			TextureString = TextureString .. _Gold .. "|TInterface\\MoneyFrame\\UI-GoldIcon:14:14:2:0|t"
		end

		if CurrentGold > 0 or CurrentSilver > 0 then
			
			if CurrentGold > 0 then

				TextureString = TextureString .. format(" %02d", CurrentSilver)

			else
			
				TextureString = TextureString .. CurrentSilver
			
			end
			
		TextureString = TextureString .. "|TInterface\\MoneyFrame\\UI-SilverIcon:14:14:2:0|t"
		
		end
		
		if CurrentCopper > 0 or CurrentSilver > 0 or CurrentGold > 0 then
		
			if CurrentSilver > 0 or CurrentGold > 0 then

				TextureString = TextureString .. format(" %02d", CurrentCopper )
				
			else
			
				TextureString = TextureString .. CurrentCopper
				
			end

		TextureString = TextureString .. "|TInterface\\MoneyFrame\\UI-CopperIcon:14:14:2:0|t"
		
		end

	else

		TextureString = "0|TInterface\\MoneyFrame\\UI-CopperIcon:14:14:2:0|t"
		
	end

	if not Raw then

		CoinsString = StringColor..NumSign..TextureString.."|r"
	else

		CoinsString = TextureString
	end

	return CoinsString

end

function GC_GetPlayerItemLevel()

	local _, PlayerItemLevel = GetAverageItemLevel()
	PlayerItemLevel = format( "%.2f", PlayerItemLevel )

	return PlayerItemLevel

end

function GC_TranslateDate( Date )

	Date = tostring( Date )

	local ShortDate, TimeOrAuto = split( " ", Date, 2)
	if not ShortDate then return nil end

local function FormatDate(Date)

	local FormattedString = ""

	local YY, MM, DD = sub( Date, 1, 2 ), sub( Date, 3, 4 ), sub( Date, 5, 6 )
	
		if ( My_GC_Settings_Local.UserDateFormat == "MM/DD/YY" ) then
	
			FormattedString = MM.."/"..DD.."/"..YY

		elseif ( My_GC_Settings_Local.UserDateFormat == "DD/MM/YY" ) then

			FormattedString = DD.."/"..MM.."/"..YY

		else

			FormattedString = YY.."/"..MM.."/"..DD

		end

		return FormattedString

end

	-- If the date was simple number in string
	if len(ShortDate) == 6 then

		return FormatDate(ShortDate)

	else

	-- If the date has an add (Compatibility with Date+Hour or Date+Auto)
	-- Reformat the date
	ShortDate = gsub(ShortDate, "/", "")
	ShortDate = FormatDate(ShortDate)

		if ( TimeOrAuto ) then
			ShortDate = ShortDate .. " " .. TimeOrAuto
		end

	end 

	return ShortDate
end

function GC_MM_Plus_Infos()

	GC_MM_Plus_OverallScore = 0
	GC_MM_Plus_HighestKeyLevel = 0
	GC_MM_Plus_HighestKeyDungeonName = ""
	
	GC_MM_Plus_UsingBackup = false

	if not GC_WOW_isRetail then return end

	GC_MM_Plus_OverallScore = C_ChallengeMode.GetOverallDungeonScore() or 0
	
	if GC_MM_Plus_OverallScore > 0 then

		local DisplayScores = C_ChallengeMode.GetMapScoreInfo()

		for i = 1, #DisplayScores do
			local Info = DisplayScores[i]

				if Info.level > GC_MM_Plus_HighestKeyLevel then
					GC_MM_Plus_HighestKeyLevel = Info.level
					GC_MM_Plus_HighestKeyDungeonName = C_ChallengeMode.GetMapUIInfo(Info.mapChallengeModeID)
				end
		end

		--- Retry until get all MM+ data
		if GC_MM_Plus_HighestKeyLevel == 0 and GC_MM_Plus_RetryCount < 10 and not GC_MM_Plus_TimerPending then
			GC_MM_Plus_RetryCount = GC_MM_Plus_RetryCount + 1

			GC_MM_Plus_TimerPending = true

			C_Timer.After(2, function()
				GC_MM_Plus_TimerPending = false
				GC_MM_Plus_Infos()
			end)
			
			GC_BuildCharDB()
			
		elseif GC_MM_Plus_HighestKeyLevel > 0 then
			GC_MM_Plus_HighestKeyLevel_Backup 		= GC_MM_Plus_HighestKeyLevel
			GC_MM_Plus_HighestKeyDungeonName_Backup = GC_MM_Plus_HighestKeyDungeonName
			GC_MM_Plus_RetryCount = 0
			GC_BuildCharDB()
		end

	else -- In case of new season or not playing MM+
		GC_MM_Plus_HighestKeyLevel = 0
		GC_MM_Plus_HighestKeyLevel_Backup = 0
		GC_MM_Plus_HighestKeyDungeonName = ""
		GC_MM_Plus_HighestKeyDungeonName_Backup = ""
		GC_MM_Plus_RetryCount = 0
		GC_BuildCharDB()
	end

end
