local addon, ns = ...;


ns.transferForm = false;
local cb = {}; cb.box = {}; cb.GUID = {}; cb.name = {}; cb.qty = {};
local transferable = {}; transferable.id = {}; transferable.name = {}; transferable.icon = {};
local myTransferForm, bTransfer, rightPane;
local transactionDetail = {};
local desc = {}; desc.top = ""; desc.middle = "";
local retainAmount = 1;
local selectedCurrencyID = 0;
local selectedChar = 0;
local resourcSlider;

local maxChar = 200;


local function AddCommas(number)
	local value = tonumber(number);		--Will accept a string too
	local ret = ""
	while (value > 1000) do
		ret = format("%03d", (value % 1000)) .. ret;
		value = floor(value / 1000);
		if value > 0 then ret = "," .. ret; end;
	end;
	if value > 0 then ret = value .. ret; end;
	if ret == "" then ret = 0; end;
	return ret;
end;

local function loadCurrency()
	--Populate the checkboxes
	desc.middle:SetText(AddCommas(0) .. "\n\n" .. AddCommas(0) .. "\n\n" .. AddCommas(C_CurrencyInfo.GetCurrencyInfo(selectedCurrencyID).quantity) );
	local chars = C_CurrencyInfo.FetchCurrencyDataFromAccountCharacters(selectedCurrencyID) or "";
	local server = "";
	for i=1, #chars do
		cb.GUID[i] = chars[i].characterGUID;
		_, _, _, _, _, _, server = GetPlayerInfoByGUID(cb.GUID[i]); 
		if server == "" then server = GetRealmName(); end;	
		cb.name[i] = chars[i].characterName .. " - " .. server; 
		cb.qty[i] = chars[i].quantity;		
		cb.box[i].Text:SetText( cb.name[i] .. " (" ..   chars[i].quantity .. ")" );
		cb.box[i]:SetChecked(false);
		cb.box[i]:Show()
	end;
	for i=#chars + 1, maxChar do
		cb.box[i]:SetChecked(false);
		cb.box[i]:Hide();
	end;	
end;

local function SetRightPane()
	local flag = false;
	local sel, cost = 0, 0;
	local qty = C_CurrencyInfo.GetCurrencyInfo(selectedCurrencyID).quantity or 0;
	selectedChar = 0
	
	for i=1, maxChar do
		if cb.box[i]:GetChecked() then
			flag = true;
			selectedChar = i;
			sel = sel + cb.qty[i] - retainAmount;
		end;
	end;
	cost = C_CurrencyInfo.GetCostToTransferCurrency(selectedCurrencyID, sel) - sel;
	bTransfer:SetEnabled(flag);
	desc.top:SetText("Moving to\n" .. GetUnitName("player") .. "\nCurrent " .. qty);
	if flag then
		transactionDetail.from:SetText("Transfering from " .. cb.name[selectedChar]);
		local max = cb.qty[selectedChar] - retainAmount;
		resourcSlider:SetMinMaxValues(retainAmount, max);
		resourcSlider.Text:SetText(max);
		resourcSlider.Low:SetText(retainAmount);
		resourcSlider.High:SetText(max);
		resourcSlider:SetValue(max);
		transactionDetail.cost:SetText( "Transaction Cost: " .. 
			C_CurrencyInfo.GetCostToTransferCurrency(selectedCurrencyID, cb.qty[selectedChar]) - cb.qty[selectedChar]);
	else
		transactionDetail.from:SetText("Select a Character to draw from");
		resourcSlider:SetMinMaxValues(0, 0);
		resourcSlider.Text:SetText("0");
		resourcSlider.Low:SetText(0);
		resourcSlider.High:SetText(0);
		resourcSlider:SetValue(0);
	end;
	desc.middle:SetText( AddCommas(sel) .. "\n\n" .. AddCommas(cost) );	
	--loadCurrency();
end;


local function TransferFrame()
	if not myTransferForm then 
		local yOff = -10;
		local f = CreateFrame("Frame", "WarbandMiserCurrencyTransfer", UIParent, "ButtonFrameTemplate"); 
		f:SetSize(550, 600);	
		_G[f:GetName() .. "TitleText"]:SetText("Warband Miser Currency Transfer");	
		_G[f:GetName() .. "Portrait"]:SetTexture("Interface\\Icons\\Achievement_reputation_08");
		f:EnableMouse(true);
		f:SetMovable(true);
		f:SetUserPlaced(true); 
		f:RegisterForDrag("LeftButton");
		f:SetScript("OnDragStart", function(self) self:StartMoving() end);
		f:SetScript("OnDragStop", function(self) self:StopMovingOrSizing(); end);
		f:SetFrameStrata("DIALOG");	
		--place a scroll frame
		local width, height = f:GetSize();
		local sContainer = CreateFrame("Frame");		
		sContainer.sFrame = CreateFrame("ScrollFrame", nil, f, "ScrollFrameTemplate");
		sContainer.sFrame:SetSize(width - 300, height - 100)
		sContainer.sFrame:SetPoint("TOPLEFT", f, "TOPLEFT", 10, -70);
		--place a scrollchild in the scroll Frame	
		sContainer:SetSize(width, height);
		sContainer.sFrame:SetScrollChild(sContainer);		
		--Add Checkboxes to the scroll Frame
		for i=1, maxChar do
			cb.box[i] = CreateFrame("CheckButton", nil, sContainer, "ChatConfigCheckButtonTemplate");
			if i == 1 then cb.box[i]:SetPoint("TOPLEFT", sContainer, "TOPLEFT", 0, 0); 
			else cb.box[i]:SetPoint("TOPLEFT",  cb.box[i-1], "TOPLEFT", 0, -25); end;
			cb.box[i]:SetScript("PostClick", function(self) SetRightPane(); end);			
			cb.box[i]:Hide();
		end;
		--Add currenciesDroplist and Populate
		local dl = CreateFrame("DropdownButton", nil, f, "WowStyle1DropdownTemplate")
		dl:SetWidth(300)
		dl:SetPoint("TOPLEFT", f,"TOPLEFT", 120, -30);	
	
		--Right pane
		local rf = CreateFrame("Frame", nil, f);
		rf:SetSize(260, 505);
		rf:SetPoint("TOPLEFT", sContainer.sFrame, "TOPRIGHT", 20, 5);
		do 		--Section 1
			rf.icon = CreateFrame("Frame", nil, rf)
			rf.icon:SetSize(48, 48);		
			local wid = (rf:GetWidth() - rf.icon:GetWidth()) / 2;
			rf.icon:SetPoint("TOPLEFT", rf, "TOPLEFT", 5, yOff);
			rf.texture = rf.icon:CreateTexture();
			rf.texture:SetAllPoints(rf.icon);
			
			-- local background = rf:CreateTexture()		--colours area to help position
			-- background:SetAllPoints(rf)
			-- background:SetColorTexture(1, 0, 1, 0.5)		
			
			desc.top = rf:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge");
			desc.top:SetPoint("TOPRIGHT", rf, "TOPRIGHT", -25, yOff);
			desc.top:SetSize(rf:GetWidth()-100, 50);
			desc.top:SetJustifyH("CENTER");
			desc.top:SetJustifyV("MIDDLE");	
			desc.top:SetText("Moving to\n" .. GetUnitName("player") .. "\nCurrent 0");
			yOff = yOff -80;
			rightPane = rf;
		end;
		do		--Section 2
			do	--Title
				local t = rf:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge");
				t:SetPoint("TOPLEFT", rf, "TOPLEFT", 0, yOff);
				t:SetSize(rf:GetWidth(), 5);
				t:SetJustifyH("CENTER");
				t:SetText("Currently Selected");
				yOff = yOff -20;
			end;
			do 	--Headings
				local t = rf:CreateFontString(nil, "OVERLAY", "GameTooltipText");
				t:SetPoint("TOPLEFT", rf, "TOPLEFT", 10, yOff);
				t:SetSize(rf:GetWidth(), 60);
				t:SetJustifyH("LEFT");
				t:SetJustifyV("TOP");
				t:SetText("Resources selected:\n\nTransfer cost:");
			end;
			do 	--Data
				desc.middle = rf:CreateFontString(nil, "OVERLAY", "GameTooltipText");
				desc.middle:SetPoint("TOPLEFT", rf, "TOPLEFT", -20, yOff);
				desc.middle:SetSize(rf:GetWidth(), 60);
				desc.middle:SetJustifyH("RIGHT");
				desc.middle:SetJustifyV("TOP");
				desc.middle:SetText( "0\n\n0");	
				yOff = yOff -55;
			end;
			do	--leave Quantity
				local t = rf:CreateFontString(nil, "OVERLAY", "GameTooltipText");
				t:SetPoint("TOPLEFT", rf, "TOPLEFT", 10, yOff);
				t:SetSize(130, 60);
				t:SetJustifyH("LEFT");
				t:SetJustifyV("TOP");
				t:SetText("Currency to leave:");	
				local eb = CreateFrame("EditBox", nil, rf, "InputBoxTemplate");
				eb:SetPoint("TOPLEFT", t, "TOPRIGHT", 20, 10);
				eb:SetEnabled(true);
				eb:SetWidth(50);
				eb:SetHeight(35);	
				eb:SetNumeric(true);	
				eb:SetText(retainAmount);
				eb:SetCursorPosition(0);
				eb:HighlightText(0,0);
				eb:SetEnabled(false);	
				eb:SetScript("OnShow", function(self) 				
					self:SetText(retainAmount);	
				end);
				eb:SetScript("OnMouseUp", function(self) 
					self:SetEnabled(true); 
					self:SetCursorPosition(0);
					self:HighlightText();
					SetRightPane();
				end);
				eb:SetScript("OnEnterPressed", function(self) 
					retainAmount = tonumber(self:GetText());
					self:SetEnabled(false);
					SetRightPane();
				end);
				eb:SetScript("OnEscapePressed", function(self) 
					self:SetEnabled(false);
					self:SetText(retainAmount);	
					SetRightPane();
				end);
				eb:SetScript("OnEditFocusLost", function(self)		
					self:SetEnabled(false);
					self:SetText(retainAmount);	
					SetRightPane();			
				end);
				yOff = yOff -50;
			end;			
		end;
		do 		--Section 3
			local w = rf:GetWidth();
			do	--Title
				local t = rf:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge");
				t:SetPoint("TOPLEFT", rf, "TOPLEFT", -10, yOff);
				t:SetSize(w, 5);
				t:SetJustifyH("CENTER");
				t:SetText("Current Transaction");
				yOff = yOff -20;
			end;
			do	--Transaction Detail
				local t = rf:CreateFontString(nil, "OVERLAY", "GameTooltipText");
				t:SetPoint("TOPLEFT", rf, "TOPLEFT", 0, yOff);
				t:SetSize(w, 25);
				t:SetJustifyH("CENTER");
				t:SetJustifyV("TOP");
				t:SetText("Moving from:");	
				transactionDetail.from = t;
			end;			
			do	--Slider
				resourcSlider = CreateFrame("Slider", nil, rf, "UISliderTemplateWithLabels")
				resourcSlider:SetPoint("TOPLEFT", transactionDetail.from, "BOTTOMLEFT", (w-225)/2, -20);
				resourcSlider:SetSize(225, 17);
				resourcSlider:SetMinMaxValues(0,0);
				resourcSlider:SetValue(0)
				resourcSlider:SetValueStep(1)
				resourcSlider:SetObeyStepOnDrag(true)
				resourcSlider:SetScript("OnValueChanged", function(self, value)
					self.Text:SetText(value)
				end)				
				yOff = yOff - 80;
			end;
			do --Cost
				local c = rf:CreateFontString(nil, "OVERLAY", "GameTooltipText");
				c:SetPoint("TOPLEFT", rf, "TOPLEFT", 0, yOff);
				c:SetSize(w, 60);
				c:SetJustifyH("CENTER");
				c:SetJustifyV("TOP");
				c:SetText("Transaction cost:");			
				transactionDetail.cost = c;		
				yOff = yOff -30;
			end;
			do 	--Transfer Button
				bTransfer = CreateFrame("Button",  nil, rf, "GameMenuButtonTemplate");
				bTransfer:SetSize(125, 25);
				bTransfer:SetText("Transfer");
				bTransfer:SetNormalFontObject("GameFontNormal");
				bTransfer:SetHighlightFontObject("GameFontHighlight");
				bTransfer:SetPoint("TOPLEFT", rf, "TOPLEFT", (w-125)/2, yOff);	
				bTransfer:SetEnabled(false);				
				bTransfer:SetScript("OnClick", function(self)
					--Do the Transfer
					C_CurrencyInfo.RequestCurrencyFromAccountCharacter(cb.GUID[selectedChar], selectedCurrencyID, cb.qty[selectedChar]);					print(resourcSlider:GetValue());
					cb.box[selectedChar]:SetChecked(false)
					SetRightPane();		--Refresh the pane
				end);
			end;
		end;
		
		if #transferable > 0 then			
			dl:SetupMenu(function(dropdown, rootDescription)
				for k,v in pairs(transferable) do
					rootDescription:CreateButton(v.name, function()
						selectedCurrencyID = v.id;
						dl:SetDefaultText(v.name); 
						loadCurrency(); 
						rightPane.texture:SetTexture(v.icon);						
					end);
				end;
			end);
			selectedCurrencyID = transferable[1].id 
			dl:SetDefaultText(transferable[1].name); 
			loadCurrency(); 
			rightPane.texture:SetTexture(transferable[1].icon);
		end;				
		myTransferForm = f;
	end;
	--loadCurrency();
	SetRightPane();
	myTransferForm:ClearAllPoints();
	myTransferForm:SetPoint("CENTER", UIParent, "CENTER");
	myTransferForm:Show();
end;

function ns:setTransferFrame()
	local btn = CreateFrame("Button",  nil, CurrencyTransferMenu, "GameMenuButtonTemplate");
	btn:SetSize(CurrencyTransferMenu.ConfirmButton:GetSize());
	btn:SetText("Miser");
	btn:SetNormalFontObject("GameFontNormal");
	btn:SetHighlightFontObject("GameFontHighlight");	
	btn:SetScript("OnClick", function(CurrencyTransferMenu)
		TransferFrame();
	end)
	CurrencyTransferMenu.CancelButton:ClearAllPoints();
	CurrencyTransferMenu.CancelButton:SetPoint("TOPLEFT", CurrencyTransferMenu.ConfirmButton, "TOPRIGHT", 5, 0);	
	btn:SetPoint("TOPLEFT", CurrencyTransferMenu.CancelButton, "TOPRIGHT", 5, 0);
	local l = floor((CurrencyTransferMenu:GetWidth() - (CurrencyTransferMenu.ConfirmButton:GetWidth() * 3) - 10) / 2);
	CurrencyTransferMenu.ConfirmButton:ClearAllPoints();
	CurrencyTransferMenu.ConfirmButton:SetPoint("TOPLEFT", CurrencyTransferMenu, "BOTTOMLEFT", l, 30);
	ns.buttonAdded = true;
	
	--Character Form Button
	local bShow = CreateFrame("Button",  nil, CharacterFrame, "GameMenuButtonTemplate");
	bShow:SetSize(80, 42);
	bShow:SetText("Transfer\nCurrency");
	bShow:SetNormalFontObject("GameFontNormal");
	bShow:SetHighlightFontObject("GameFontHighlight");
	bShow:SetPoint("TOPLEFT", CharacterFrame, "TOPLEFT", 60, -20);	
	bShow:SetFrameStrata("HIGH");
	bShow:SetScript("OnClick", function(self)
		ns:GetTransferableCurrencies();
	end)	
end;

function ns:GetTransferableCurrencies()
	local colapseList = {};
	local sz = C_CurrencyInfo.GetCurrencyListSize();
	local info, currencyID, lnk;
	
	transferable = {};
	if sz > 0 then
		--expand all
		local index = 1;
		local icon;
		while index <= sz do
			info = C_CurrencyInfo.GetCurrencyListInfo(index);
			if not info.isHeaderExpanded then
				tinsert(colapseList, 1, index)						--save the position so we can colapse later
				C_CurrencyInfo.ExpandCurrencyList(index, true);		--expand this node
				sz = C_CurrencyInfo.GetCurrencyListSize();			--get the now larger list size
			end;
			lnk = C_CurrencyInfo.GetCurrencyListLink(index);
			if lnk then 
				currencyID = C_CurrencyInfo.GetCurrencyIDFromLink(lnk);				--get the currencyID
				C_CurrencyInfo.RequestCurrencyDataForAccountCharacters();
				if C_CurrencyInfo.IsAccountTransferableCurrency(currencyID) then	--test if transferable
					local t = {};													--save transferable currency
					icon = "|T"..info.iconFileID..":12|t ";
					t.id = currencyID; t.name = icon .. info.name; t.icon = info.iconFileID;
					tinsert(transferable, t);
				end;
			end;
			index = index + 1;
		end;				
		TransferFrame();				--Show the transfer Form
		--Restore the currency list back to how the user had it
		for _,v in ipairs(colapseList) do
			C_CurrencyInfo.ExpandCurrencyList(v, false);
		end;
	end;
end;


