local addonName, addon = ...
local childName = addon['childName']
local child = addon[childName]
local db, mailSum, mailRec, player, dbb, dbr, dbf, L, faction, realm
local events = child['events']
local mailframes = {}
local posFrame = CreateFrame("Frame")
posFrame:SetSize(32,1)
posFrame:SetPoint("TOPRIGHT",SendMailFrame,"TOPRIGHT",-10,-12)
posFrame:SetScript("OnEvent", function(self, event, ...)
	self:UnregisterEvent('MAIL_FAILED')
	self:UnregisterEvent('MAIL_SEND_SUCCESS')
	if(event == "MAIL_SEND_SUCCESS") then
		if(mailRec and mailSum) then
			dbr[mailRec]['incoming'] = (dbr[mailRec]['incoming'] or 0) + mailSum
			print(L['Success'](mailRec,mailSum))
			mailframes[mailRec]:Hide()
		end
	elseif(event == "MAIL_FAILED") then
		print(L['Fail'])
	end
	mailRec = nil
	mailSum = nil
end)
local lastframe = posFrame
local function GetFactionList()
	local n,m,_
	local l = {}
	if(addon['db']['sv']['profileKeys']) then
		for k,v in pairs(addon['db']['sv']['profileKeys']) do
			n,_,m = strsplit(' ',k,3)
			if(n) then
				if(m == realm) then
					if(faction == dbr[n]['faction']) then
						l[n] = true
					end 
				end
			end
		end
	end
	return l
end
local function getDeliver(name)
	if(not dbr[name] or not dbr[name]['currentGold']) then return 0 end
	local sendSum,offset
	local lim, mon
	if(dbb['banker'] ~= player) then
		lim = dbb['maxLimit'] or 100
		mon = GetMoney()
		sendSum = mon - lim*10000 - 30
		offset = 0
	else
		lim = dbb['minLimit'] or 100
		mon = dbr[name]['currentGold']
		sendSum = lim*10000 - mon
		offset = 30
	end
	if(sendSum + offset > GetMoney()) then
		sendSum = GetMoney()
	end
	return sendSum - (dbb['banker'] == name and 0 or (dbr[name]['incoming'] or 0))
end
local function Click(self,button)
	local sendSum = getDeliver(self['destName'])
	if(child:IsTwink(self['destName']) and self['destName']~=player) then
		if(sendSum>0) then
			if(SetSendMailMoney(sendSum)) then
				posFrame:RegisterEvent('MAIL_SEND_SUCCESS')
				posFrame:RegisterEvent('MAIL_FAILED')
				mailRec = self['destName']
				mailSum = sendSum
				SendMail(self['destName'],L['Subject'],nil)
			end
		end
	end
end
local function Mouse(self)
	local tip = GameTooltip
	tip:SetOwner(self, "ANCHOR_BOTTOM")
	tip:ClearLines() 
	self['tooltip'] = tip
	if(dbb['banker'] ~= player) then
		tip:AddLine(format("%s %s",L['Bankier'],dbb['banker']))
		tip:AddLine(format("%s %s",L['Goldgrenze'],dbb['maxLimit']))
	else
		tip:AddLine(format("%s %s",L['Empfaenger'],self['destName']))
		tip:AddLine(format("%s %s",L['Goldgrenze'],dbb['minLimit']))
	end
	local sendSum = getDeliver(self['destName'])
	tip:AddLine(format("%s %s",L['Sende'],GetCoinTextureString(sendSum)))
	tip:Show()
end
local function MouseOut(self)
	self['tooltip']:Hide()
end
local function MainFrame(name)
	if(getDeliver(name)<0) then return nil end
	local mailframe = mailframes[name] and mailframes[name] or CreateFrame("Button",nil,SendMailFrame,"ActionButtonTemplate SecureActionButtonTemplate")
	mailframe:SetSize(32,32)
	mailframe:SetPoint("TOPRIGHT",lastframe,"BOTTOMRIGHT",0,-8)
	mailframe:EnableMouse(true)
	mailframe:RegisterForClicks("AnyUp")
	mailframe['destName'] = name
	mailframe:SetScript("OnClick", Click)
	mailframe:SetScript("OnEnter", Mouse)
	mailframe:SetScript("OnLeave", MouseOut)
	if(not mailframe['texture']) then
		mailframe['texture'] = mailframe:CreateTexture(nil,"BACKGROUND")
		mailframe['texture']:SetTexture("Interface\\Icons\\INV_Misc_Bag_10_Blue")
		mailframe['texture']:SetAllPoints(mailframe)
		mailframe['texture']:SetPoint("CENTER",0,0)
		mailframe['texture']:Show()
	end
	return mailframe
end
local function buildMailFrames()
	local banker = dbb['banker']
	if(banker and mailframes) then
		for k,v in pairs(mailframes) do
			mailframes[k]:Hide()
			mailframes[k] = nil
		end
		mailframes = {}
	end
	if(db["disableBanker"]) then return end
	posFrame:Show()
	lastframe = posFrame

	if(player == banker) then
		local fl = GetFactionList()
		if(fl) then
			local money = GetMoney()
			for k,v in pairs(fl) do
				if(k ~= banker) then
					if(getDeliver(k) > 0 and getDeliver(k) < money - 10000) then
						mailframes[k] = MainFrame(k)
						mailframes[k]:Show()
						lastframe = mailframes[k]
					end
				end
			end
		end
	else
		local money = GetMoney()
		if(getDeliver(banker) > 0 and getDeliver(banker) < money - 10000) then
			mailframes[banker] = MainFrame(banker)
			mailframes[banker]:Show()
		end
	end
end
function events:MAIL_SHOW()
	buildMailFrames()
end
local init = {
	Setup = function(self)
		player = UnitName('player')
		L = child['storage']['L']
		db = child['storage']['db']
		dbr = child['storage']['dbr']
		dbf = child['storage']['dbf']
		dbb = dbf['banker']
		faction = child['storage']['faction']
		realm = child['storage']['realm']
	end
}
addon.RegisterCallback(init, format("Init%s", childName), 'Setup')