--[[
	Team Rating Arena Point Formulae

	X = Team Rating, Y = Arena Points

	If X<=1500: Y = 0.38*X-194
	(note: this calculation can go negative, but will be floored at 0)

	If X>1500 Y = 1426.79/(1+918.836*Power(2.71828, -0.00386405*X))

	The 2v2 and 3v3 penalties are 70% for 2v2 and 80% for 3v3
--]]

--Constants-----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------

local tag = "aquafusion arena points";
local version = "1.6";

--how many team types are there in arena right now?
	afap_numMaxTeams = 3;

--create our arena tables
	afap_arena = {};
		afap_arena["points"] = {};
		afap_arena["fonts"] = {
			["insufficient"] 	= '656565',
			["normal"]		= 'ffffff',
			["most"]		= '00ff00',
		};



--Library-------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------

function afap_updateStuff()
	for i=1,afap_numMaxTeams do
		teamName, teamSize, teamRating, weekPlayed, weekWins, seasonPlayed, seasonWins, playerPlayed, teamRank = GetArenaTeam(i);
		if (teamName) then
			--current counter is a proper ID for an arena team, so let's put some points into our array!
			afap_arena["points"][teamSize] = afap_calculatePoints(i);
		end
	end

	--sort the findings by the points earned, least to first
	afap_arenaS = afap_arraySort(afap_arena["points"],"key");

	for k, v in pairs (afap_arenaS) do
		DEFAULT_CHAT_FRAME:AddMessage("Sort Index: "..k..", Sorted Value: "..v);
	end
	for k, v in pairs (afap_arena["points"]) do
		DEFAULT_CHAT_FRAME:AddMessage("Key: "..k..", Value: "..v);
	end
end

function afap_arraySort(array,target)
	--array as array, target as string(value or key sorting)
	sortedInstance = {};
	sortedProgress = {};
	currentIndex = 1;

	if (target=="key") then
		for k, v in pairs (array) do
			if (sortedProgress[k] ~= 1) then
				--only focus the current key if it hasn't been sorted already
				focusKey = k;
				focusValue = v;
				for k, v in pairs (array) do
					if (sortedProgress[k] ~= 1) then
						--only compare the keys if the target key hasn't already been sorted
						if (focusKey <= k) then
							smallestKey = focusKey;
							smallestKeyValue = focusValue;
							
						else
							smallestKey = k;
							smallestKeyValue = v;
						end
						sortedProgress[smallestKey] = 1;
						DEFAULT_CHAT_FRAME:AddMessage(smallestKey.." was added to the sort progress and will be ignored the rest of this sort.");
						sortedInstance[currentIndex] = smallestKey;
						currentIndex = currentIndex+1
					end
				end
			end
		end
		sortedProgress = nil;
		return sortedInstance;
	elseif (target=="value") then
		
	else
		return array;
	end
end

function afap_eligable(playerPlayed,weekPlayed)
	playedPercent = (playerPlayed / weekPlayed) * 100;
	if (weekPlayed < 10 or playedPercent < 30) then
		--nope, no points this week!
		return false;
	else
		--yep, points are good!
		return true;
	end
end

function afap_calculatePoints(id)	
	if (teamRating < 1500) then
		teamPoints = 0.38 * teamRating - 194;
	else
		teamPoints = 1426.79 / (1 + (918.836 * (2.71828 ^ (-0.00386405 * teamRating))));
	end

	--time to figure in that nasty team size penalty!
		if (teamSize == 2) then
			teamPoints = teamPoints * 0.70;
		elseif (teamSize == 3) then
			teamPoints = teamPoints * 0.80;
		end

	--and in the case of a negative number, lets floor the points to zero :)
		if (teamPoints < 0 ) then
			teamPoints = 0;
		end

	--phew, now we can send those points on over for the rest of this script to work with!
		return round(teamPoints,0);
end
--Bootup--------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------

function afap_onload()
	--register events
		afap_overlay:RegisterEvent("PLAYER_ENTERING_WORLD");
		afap_overlay:RegisterEvent("ARENA_TEAM_UPDATE");
		afap_overlay:RegisterEvent("ARENA_TEAM_ROSTER_UPDATE");
		afap_overlay:RegisterEvent("PLAYER_PVP_KILLS_CHANGED");
		afap_overlay:RegisterEvent("PLAYER_PVP_RANK_CHANGED");
		afap_overlay:RegisterEvent("HONOR_CURRENCY_UPDATE");

	--hide the default arena icon, label, points,a nd tooltip since we have our own to use ;)
		PVPFrameArenaPoints:Hide();
		PVPFrameArenaIcon:Hide();
		PVPFrameArenaLabel:Hide();
		PVPFrameArena:Hide();

		PVPFrameHonorPoints:Hide();
		PVPFrameHonorIcon:Hide();
		PVPFrameHonorLabel:Hide();
		PVPFrameHonor:Hide();

		afap_CalcButton:Hide();

		local factionGroup = UnitFactionGroup("player");
		if ( factionGroup ) then
			afap_overlay_HonorIcon:SetTexture("Interface\\TargetingFrame\\UI-PVP-"..factionGroup);
		end

	--give an initial update to our data
		afap_updateinfo();

		afap_CalcButton_normal:SetTexture("Interface\\AddOns\\af_arenapoints\\gui\\calculator");
		afap_CalcButton_pushed:SetTexture("Interface\\AddOns\\af_arenapoints\\gui\\calculator-push");
		afap_CalcButton_highlight:SetTexture(nil);

		afap_calculator:SetBackdropColor(0,0,0);

	--let the user know the addon loaded successfully
		DEFAULT_CHAT_FRAME:AddMessage("|cffffdd00[" .. tag .. "]:|r v" .. version .. " loaded.");
end

function afap_onevent(event)
	--afap_updateStuff();
	afap_updateinfo();
end

function afap_updateinfo()
	--honor
		--collect some data
			hk, cp = GetPVPSessionStats();
			points = GetHonorCurrency();
			total = cp + points;

		--show the data
			afap_overlay_HonorPoints:SetText("|cffffffffHONOR:  |r|cffffcc00"..points.."|r  +  |cff00ff00"..cp.."|r|cffffffff  =  |r|cff00ccff"..total.."|r");

	--arena
		--lets figure out how many points each of our three teams are getting us this week.
			arenaPoints1, size1 = afap_getTeamPoints(1);
			arenaPoints2, size2 = afap_getTeamPoints(2);
			arenaPoints3, size3 = afap_getTeamPoints(3);

		--arrange the output of the explanation in order of 2v2 - 5v5
			--2v2 team
				if (size1 == 2) then
					v2Points = arenaPoints1;
				elseif (size2 == 2) then
					v2Points = arenaPoints2;
				elseif (size3 == 2) then
					v2Points = arenaPoints3;					
				else
					v2Points = 0;
				end

			--3v3 team
				if (size1 == 3) then
					v3Points = arenaPoints1;
				elseif (size2 == 3) then
					v3Points = arenaPoints2;
				elseif (size3 == 3) then
					v3Points = arenaPoints3;					
				else
					v3Points = 0;
				end

			--5v5 team
				if (size1 == 5) then
					v5Points = arenaPoints1;
				elseif (size2 == 5) then
					v5Points = arenaPoints2;
				elseif (size3 == 5) then
					v5Points = arenaPoints3;					
				else
					v5Points = 0;
				end

		--now time to figure out which one earned us the most points, shall we?
			if (v5Points >= v2Points and v5Points >= v3Points) then
				thePoints = v5Points;
				--if it is zero we will keep it white, otherwise it should be green
					if (v5Points == 0) then
						v5PointsText = ("|cffffffff"..v5Points.."|r");
					else					
						v5PointsText = ("|cff00ff00"..v5Points.."|r");
					end
				--make the rest white by default
					v2PointsText = ("|cffffffff"..v2Points.."|r");
					v3PointsText = ("|cffffffff"..v3Points.."|r");
			elseif (v3Points >= v2Points and v3Points >= v5Points) then
				thePoints = v3Points;
				--if it is zero we will keep it white, otherwise it should be green
					if (v3Points == 0) then
						v3PointsText = ("|cffffffff"..v3Points.."|r");
					else					
						v3PointsText = ("|cff00ff00"..v3Points.."|r");
					end
				--make the rest white by default
					v2PointsText = ("|cffffffff"..v2Points.."|r");
					v5PointsText = ("|cffffffff"..v5Points.."|r");
			elseif(v2Points >= v5Points and v2Points >= v3Points) then
				thePoints = v2Points;
				--if it is zero we will keep it white, otherwise it should be green
					if (v2Points == 0) then
						v2PointsText = ("|cffffffff"..v2Points.."|r");
					else					
						v2PointsText = ("|cff00ff00"..v2Points.."|r");
					end
				--make the rest white by default
					v3PointsText = ("|cffffffff"..v3Points.."|r");
					v5PointsText = ("|cffffffff"..v5Points.."|r");
			else
				thePoints = 0;
			end
	
		--and if we add that to what we already own, we get the following total at the end of the week...
			arenaPointsTotal = thePoints + GetArenaCurrency();
	
		--so, how about we slap all of that on the pvp/honor page?
			--first the numbers that matter
				afap_overlay_AllPoints:SetText("|cffffffffARENA:|r  |cffffcc00"..GetArenaCurrency().."|r|cffffffff  +  |r|cff00ff00"..thePoints.."|r|cffffffff  =  |r|cff00ccff"..arenaPointsTotal.."|r");
			--and then a breakdown of where the numbers are coming from
				afap_overlay_Explain:SetText("|cff7777772v2:|r  "..v2PointsText.."|cff777777      3v3:|r  "..v3PointsText.."|cff777777      5v5:|r  "..v5PointsText);
	
		--And now that it's all filled in, lets align it!
			afap_setPlacement();
end

function afap_getTeamPoints(id)
	
	--extract the information
		teamName, teamSize, teamRating, weekPlayed, weekWins, seasonPlayed, seasonWins, playerPlayed, teamRank = GetArenaTeam(id);

	--did the team play at least 30% of the matches this week AND play at least 10 games?
		playedPercent = (playerPlayed / weekPlayed) * 100;
		if (weekPlayed < 10 or playedPercent < 30) then
			--nope, no points this week!
				teamPoints = 0;
		else
			--player did in fact meet requirements to get points, let's figure out which algorithm is going to be used, shall we?
				if (teamRating < 1500) then
					teamPoints = 0.38 * teamRating - 194;
				else
					teamPoints = 1426.79 / (1 + (918.836 * (2.71828 ^ (-0.00386405 * teamRating))));
				end

			--time to figure in that nasty team size penalty!
				if (teamSize == 2) then
					teamPoints = teamPoints * 0.70;
				elseif (teamSize == 3) then
					teamPoints = teamPoints * 0.80;
				end

			--and in the case of a negative number, lets floor the points to zero :)
				if (teamPoints < 0 ) then
					teamPoints = 0;
				end
		end

	--phew, now we can send those points on over for the rest of this script to work with!
		return round(teamPoints,0), teamSize;
end

function afap_setPlacement()
	--get the width of the containing frame and our 3 lines
		frameWidth = PVPFrame:GetWidth();

		honorwidth = afap_overlay_HonorPoints:GetWidth() + afap_overlay_HonorIcon:GetWidth();

		line1width = (afap_overlay_AllPoints:GetWidth() + afap_overlay_Icon:GetWidth());
		line2width = afap_overlay_Explain:GetWidth();


		honorcenterPoint = ((frameWidth - honorwidth) / 2) - 7;
		centerPoint = ((frameWidth - line1width) / 2) - 10;

	--now lets move stuff!
		--where should the first line go?
			afap_overlay_Icon:SetPoint("topleft", "PVPFrame", "topleft", centerPoint, -133);
			afap_overlay_HonorIcon:SetPoint("topleft", "PVPFrame", "topleft", honorcenterPoint, -40);

		--and we should nudge line 2 over so that it centers under line 1 including the icon
			afap_overlay_Explain:SetPoint("top", "afap_overlay_AllPoints", "bottom", -((afap_overlay_Icon:GetWidth()/2) + 1), -11)
end

function round(num, idp)
	local mult = 10^(idp or 0);
	return floor(num * mult + 0.5) / mult;
end

function afap_CalcButtonClick()
	--[[
		PlaySound("igCharacterInfoTab");
		if (afap_calculator:IsVisible()) then
			afap_calculator:Hide();
		else
			afap_calculator:Show();
		end
	--]]
end