local toc, privateData = ...
local AddonId = toc.identifier

EM.Utility = {}
EM.Utility.Callback = {}
EM.Temp.PopupTest = false

local tableInsert = table.insert
local tableSort = table.sort

function EM.Utility.ClearFocus()
	EM.UI.Settings.txfDeleteCustom:SetKeyFocus(true)
	EM.UI.Settings.txfDeleteCustom:SetKeyFocus(false)
	EM.UI.Send.ToField:SetText("")
	EM.UI.Send.SubjectField:SetText("")
	EM.UI.Send.MessageField:SetText("")
	EM.UI.Send.SendMoneyRadio2.Texture:SetTexture(AddonId, "gfx/radiobutton_selected.png")
	EM.UI.Send.CoDRadio2.Texture:SetTexture(AddonId, "gfx/radiobutton.png")
	EM.UI.Send.SentMoneyText:SetText("Amount to Send")
	EM.UI.Send.radioSelected = "Money"
	EM.UI.Send.SentMoneySilver:SetText("")
	EM.UI.Send.SentMoneyGold:SetText("")
	EM.UI.Send.SentMoneyPlat:SetText("")
	EM.UI.Send.Attachments = {}
	EM.Send.Fill()
	EM.UI.Send.CostSilver:SetText('25')
	EM.UI.Send.CostGoldIcon:SetVisible(false)
	EM.UI.Send.CostGold:SetText('')
	EM.UI.Send.CostPlatIcon:SetVisible(false)
	EM.UI.Send.CostPlat:SetText('')
	EM.UI.Send.btnSend:SetEnabled(false)
end

function EM.Utility.ClearMessage()
	EM.UI.Settings.txfDeleteCustom:SetKeyFocus(true)
	EM.UI.Settings.txfDeleteCustom:SetKeyFocus(false)
	EM.UI.Send.ToField:SetText("")
	EM.UI.Send.SubjectField:SetText("")
	EM.UI.Send.MessageField:SetText("")
	EM.UI.Send.SendMoneyRadio2.Texture:SetTexture(AddonId, "gfx/radiobutton_selected.png")
	EM.UI.Send.CoDRadio2.Texture:SetTexture(AddonId, "gfx/radiobutton.png")
	EM.UI.Send.SentMoneyText:SetText("Amount to Send")
	EM.UI.Send.radioSelected = "Money"
	EM.UI.Send.SentMoneySilver:SetText("")
	EM.UI.Send.SentMoneyGold:SetText("")
	EM.UI.Send.SentMoneyPlat:SetText("")
	EM.Send.Fill()
	EM.UI.Send.CostSilver:SetText('25')
	EM.UI.Send.CostGoldIcon:SetVisible(false)
	EM.UI.Send.CostGold:SetText('')
	EM.UI.Send.CostPlatIcon:SetVisible(false)
	EM.UI.Send.CostPlat:SetText('')
	EM.UI.Send.btnSend:SetEnabled(false)
end

function EM.Utility.ClearAttachments()
	EM.UI.Send.Attachments = {}
	EM.Send.Fill()
end

function EM.Utility.Coin(coin)

	if not coin then return end

	local plat = 0
	local gold = 0
	local silver = 0
	local len = string.len(coin)

	if len < 5 then
		repeat
			coin = "0" .. coin
		until string.len(coin) == 5
		len = string.len(coin)
	end

	if coin == 0 or nil then
		return plat,gold,silver
	else
		plat = string.sub(coin,1,len-4)
		gold = string.sub(coin,len-3,len-2)
		silver = string.sub(coin,len-1,len)
		return plat,gold,silver
	end
end

function EM.Utility.AttachSetup()

	local attachments = {}
	EM.Temp.attachmentsType = {}

	if #EM.UI.Send.Attachments == 0 then return end

	if #EM.UI.Send.Attachments > 6 then
		for idx = 1, 6, 1 do
			table.insert(attachments, EM.UI.Send.Attachments[1][1].key)
			table.insert(EM.Temp.attachmentsType, EM.UI.Send.Attachments[1][1].typeID)
			table.remove(EM.UI.Send.Attachments, 1)
		end
		EM.Send.Fill()
	else
		for slot, data in ipairs(EM.UI.Send.Attachments) do
			table.insert(attachments, data[1].key)
			table.insert(EM.Temp.attachmentsType, data[1].typeID)
		end
		EM.UI.Send.Attachments = {}
		EM.Send.Fill()
	end
	return attachments
end

function EM.Utility.RecipientSetup()

	local recipient = nil
	local multipleRecipients = false

	if #EM.UI.Send.Recipients == 0 then return end

	if #EM.UI.Send.Recipients > 1 then
		multipleRecipients = true
		recipient = EM.UI.Send.Recipients[1]
		table.remove(EM.UI.Send.Recipients, 1)
	else
		multipleRecipients = false
		recipient = EM.UI.Send.Recipients[1]
		if #EM.UI.Send.Attachments == 0 then
			table.remove(EM.UI.Send.Recipients, 1)
		end
	end

	return recipient, multipleRecipients
end

function EM.Utility.Popup(numbtn, message, callFunc)

	local popupWindow = {}
	local popup = {}

	if EM.UI.PopupWindow then
		EM.UI.PopupWindow:SetVisible(true)
		EM.UI.PopupWindow.messagetxt:SetText(message)
	else
		popup = UI.CreateFrame("Texture", "emPopupWindow", EM.Context.Main)
			popup:SetPoint("CENTER", UIParent, "CENTER")
			popup:SetTexture(AddonId, "gfx/popup.png")
			popup:SetLayer(90)

		popup.okbtn = UI.CreateFrame("RiftButton", "popupOK", popup)
			popup.okbtn:SetText("OK")
			popup.okbtn:SetPoint("BOTTOMRIGHT", popup, "BOTTOMCENTER", 5, -15)
			popup.okbtn:SetEnabled(true)
			popup.okbtn:EventAttach(Event.UI.Button.Left.Press,
				function()
					EM.UI.PopupWindow:SetVisible(false)
					EM.Temp.PopupTest = true
					if callFunc then
						EM.Utility.Callback.Popup(callFunc)
					else
						return
					end
				end, "popupOkLeftPress")

		popup.cancelbtn = UI.CreateFrame("RiftButton", "popupCancel", popup)
			popup.cancelbtn:SetText("CANCEL")
			popup.cancelbtn:SetPoint("BOTTOMLEFT", popup, "BOTTOMCENTER", -2, -15)
			popup.cancelbtn:SetEnabled(true)
			popup.cancelbtn:EventAttach(Event.UI.Button.Left.Press,
				function()
					EM.UI.PopupWindow:SetVisible(false)
					EM.Temp.PopupTest = nil
					if callFunc then
						EM.Utility.Callback.Popup(callFunc)
					else
						return
					end
				end, "popupCancelLeftPress")

		popup.messagetxt = UI.CreateFrame("Text", "popupMessage", popup)
			popup.messagetxt:SetText(message)
			popup.messagetxt:SetFontSize(22)
			popup.messagetxt:SetPoint("TOPCENTER", popup, "TOPCENTER", 0, 10)
			popup.messagetxt:SetFontColor(0.85,0.80,0.62,1)
			popup.messagetxt:SetVisible(true)

		EM.UI.PopupWindow = popup
	end

	if numbtn == 1 then
		EM.UI.PopupWindow.okbtn:ClearAll()
		EM.UI.PopupWindow.okbtn:SetPoint("BOTTOMCENTER", EM.UI.PopupWindow, "BOTTOMCENTER", 0, -15)
		EM.UI.PopupWindow.cancelbtn:SetEnabled(false)
		EM.UI.PopupWindow.cancelbtn:SetVisible(false)
	end
end

function EM.Utility.Callback.Popup(callFunc)
	callFunc()
end

function EM.Utility.InventorySlotCheck()
	local total = 0
	local free = 0

	for i=1,7,1 do
		for slot, value in pairs(Inspect.Item.List("si0" .. i)) do
			total = total + 1
			if value == false then
				free = free + 1
			end
		end
	end

	if free > 0 then
		return true
	else
		return false
	end
end

function EM.Utility.SendBtnCheck()
	local radio = EM.UI.Send.radioSelected
	local to, subject, plat, gold, silver, attachments
	if EM.UI.Send.ToField:GetText() ~= (nil or "") then
		to = true
	else
		to = false
	end
	if EM.UI.Send.SubjectField:GetText() ~= (nil or "") then
		subject = true
	else
		subject = false
	end
	if EM.UI.Send.SentMoneyPlat:GetText() ~= (nil or "") then
		plat = true
	else
		plat = false
	end
	if EM.UI.Send.SentMoneyGold:GetText() ~= (nil or "") then
		gold = true
	else
		gold = false
	end
	if EM.UI.Send.SentMoneySilver:GetText() ~= (nil or "") then
		silver = true
	else
		silver = false
	end
	if #EM.UI.Send.Attachments > 0 then
		attachments = true
	else
		attachments = false
	end
	if radio == "Money" then
		if to == true and subject == true then
			EM.UI.Send.btnSend:SetEnabled(true)
		else
			EM.UI.Send.btnSend:SetEnabled(false)
		end
	elseif radio == "CoD" then
		if to == true and subject == true and attachments == true and (plat == true or gold == true or silver == true) then
			EM.UI.Send.btnSend:SetEnabled(true)
		else
			EM.UI.Send.btnSend:SetEnabled(false)
		end
	end
end

function EM.Utility.AddDeletedUnix()
	for id, data in pairs(EasyMailTable[EM.PlayerName].Inbox) do
		if not data.deletedUnix then
			if not data.deleted then
				EasyMailTable[EM.PlayerName].Inbox[id].deletedUnix = 9999999999
				EasyMailTable[EM.PlayerName].Inbox[id].deleted = os.date("%x %X", EasyMailTable[EM.PlayerName].Inbox[id].deletedUnix)
			else
				local deleted = data.deleted
				local year = "20" .. string.sub(deleted, 7, 8)
				local month = string.sub(deleted, 1, 2)
				local day = string.sub(deleted, 4, 5)
				local hour = string.sub(deleted, 10, 11)
				local minute = string.sub(deleted, 13, 14)
				local second = string.sub(deleted, 16, 17)
				local deletedUnix = os.time({year = year, month = month, day = day, hour = hour, min = minute, sec = second})
				EasyMailTable[EM.PlayerName].Inbox[id].deletedUnix = deletedUnix
			end
		end
	end
	for sid, sdata in pairs(EasyMailTable[EM.PlayerName].Sent) do
		if not sdata.timesentUnix then
			if not sdata.timesent then
				EasyMailTable[EM.PlayerName].Sent[sid].timesentUnix = 9999999999
				EasyMailTable[EM.PlayerName].Sent[sid].timesent = os.date("%x %X", EasyMailTable[EM.PlayerName].Sent[sid].timesentUnix)
			else
				local timesent = sdata.timesent
				local year = "20" .. string.sub(timesent, 7, 8)
				local month = string.sub(timesent, 1, 2)
				local day = string.sub(timesent, 4, 5)
				local hour = string.sub(timesent, 10, 11)
				local minute = string.sub(timesent, 13, 14)
				local second = string.sub(timesent, 16, 17)
				local timesentUnix = os.time({year = year, month = month, day = day, hour = hour, min = minute, sec = second})
				EasyMailTable[EM.PlayerName].Sent[sid].timesentUnix = timesentUnix
			end
		end
	end
end

function EM.Utility.CreateNewDataTable()
	local archiveTab = EM.UI.Archive
	EM.NewDataTable = {}
	EM.NewDataTable.Inbox = {}
	EM.NewDataTable.Sent = {}
	EM.NewDataTable.Filter = {}

	if archiveTab.radioSelected2 then
		if archiveTab.radioSelected2 == "Received" then
			EM.NewDataTable.Used = "Inbox"
		elseif archiveTab.radioSelected2 == "Sent" then
			EM.NewDataTable.Used = "Sent"
		end
	else
		EM.NewDataTable.Used = "Inbox"
	end

	for id, data in pairs(EasyMailTable[EM.PlayerName].Inbox) do
		tableInsert(EM.NewDataTable.Inbox, data)
	end
	for id, data in pairs(EasyMailTable[EM.PlayerName].Sent) do
		tableInsert(EM.NewDataTable.Sent, data)
	end
	tableSort(EM.NewDataTable.Inbox, function(a,b) return a.deletedUnix > b.deletedUnix end)
	tableSort(EM.NewDataTable.Sent, function(a,b) return a.timesentUnix > b.timesentUnix end)
end

function EM.Utility.MouseMove(handle, xcoord, ycoord)
	if EM.UI.Contacts.Window and EM.UI.Contacts.Window.leftDown then
		local points = EM.UI.Contacts.Window:ReadAll()
		local x,y
		for key, value in pairs(points.x) do
			if type(key) == "number" and key >= 0 then
				x = key
			end
		end
		for key, value in pairs(points.y) do
			if type(key) == "number" and key >= 0 then
				y = key
			end
		end
		EM.UI.Contacts.Window:ClearPoint(x,y)
		EM.UI.Contacts.Window:SetPoint(EM.UI.Contacts.Window.x, EM.UI.Contacts.Window.y, EM.Context.Contacts, "TOPLEFT", xcoord, ycoord)
	elseif EM.UI.MailWindow and EM.UI.MailWindow.leftDown then
		local points = EM.UI.MailWindow:ReadAll()
		local x,y
		for key, value in pairs(points.x) do
			if type(key) == "number" and key >= 0 then
				x = key
			end
		end
		for key, value in pairs(points.y) do
			if type(key) == "number" and key >= 0 then
				y = key
			end
		end
		EM.UI.MailWindow:ClearPoint(x,y)
		EM.UI.MailWindow:SetPoint(EM.UI.MailWindow.x, EM.UI.MailWindow.y, EM.Context.Main, "TOPLEFT", xcoord, ycoord)
	end
end

Command.Event.Attach(Event.Mouse.Move, EM.Utility.MouseMove, AddonId .. "_MouseMove")