local _, core = ...;

WC_Lib.spts              = {["Zérebys-Antonidas"] = 2};
WC_Lib.fullNamePlayer    = "";
local CurrentPlayerScore = 0;
local genders            = {"unknown", "male", "female"};
local pathPortrait       = "Interface/CHARACTERFRAME/TEMPORARYPORTRAIT-";
local MAX_NUMBER_PLAYER  = 40;
local fontText           = "Fonts\\FRIZQT__.TTF";
if GetLocale() == "ruRU" then fontText = "Interface\\AddOns\\WoWChallenger\\fonts\\FRIZQT__CYR.TTF"	end

function WC_Lib.GetGuidesByWoWChallengerByLocal()
	local array        = {};
	local localization = GetLocale();
	for i = 1, #WC_Guides do
		local collection = WC_Guides[i];
		if collection.av_settings.createBy == "WoW Challenger" and
		   core.L["LangID"][collection.lang[1]] == localization then
			table.insert(array, collection);
		end
	end
	return array;
end

local function Split(s, delimiter)
    result = {};
    for match in (s..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match);
    end
    return result;
end

local function checkIfHaveName(name, tableCheck)
	for i = 1, #tableCheck do
		if (name == tableCheck[i]) then
			return true;
		end
	end
	return false;
end

--- ===== CAMPAIGNS ===== ---
local function GetCampaignScore(onlyNbDone)
	local score  = 0;
	local nbDone = 0;
	for i = 1, #Campaign1 do
		if (Campaign1[i].done == true) then
			score  = score + 5;
			nbDone = nbDone + 1;
			if (core.DBcampaign[1].fights[i].boss == true) then
				score = score + 5;
			end
		end
	end
	for j = 1, #Campaign2 do
		if (Campaign2[j].done == true) then
			score  = score + 15;
			nbDone = nbDone + 1;
			if (core.DBcampaign[2].fights[j].boss == true) then
				score = score + 10;
			end
		end
	end
	for k = 1, #Campaign3 do
		if (Campaign3[k].done == true) then
			score  = score + 35;
			nbDone = nbDone + 1;
			if (core.DBcampaign[3].fights[k].boss == true) then
				score = score + 20;
			end
		end
	end
	for l = 1, #Campaign4 do
		if (Campaign4[l].done == true) then
			score  = score + 50;
			nbDone = nbDone + 1;
			if (core.DBcampaign[4].fights[l].boss == true) then
				score = score + 30;
			end
		end
	end
	if onlyNbDone then return nbDone end
	return score;
end

local function GetNbDoneCampaignsByCurrentLevel(infoCampaign)
	local nbDone  = 0;
	local nbLevel = 0;
	for i = 1, #core.DBcampaign do
		nbLevel = nbLevel + #core.DBcampaign[i].fights;
		if (infoCampaign >= nbLevel) then
			nbDone = nbDone + 1;
		end
	end
	return nbDone.."/"..#core.DBcampaign;
end

--- ===== CHALLENGES ===== ---
local function GetInfoChallengesDone()
	local ret = "";
	for i = 1, #core.DBchallenge.data do
		for j = 1, #core.DBchallenge.data[i] do
			ret = ret..math.floor(core.libs.progressPourcent(core.DBchallenge.data[i][j]))..",";
		end
	end
	ret = ret:sub(1, -2); -- enlever la virgule de fin
	return ret;
end

local function GetNbDoneChallenges(infoChallenge)
	local challenges = Split(infoChallenge, ",");
	local nbDone     = 0;
	for i = 1, #challenges do
		if (tonumber(challenges[i]) == 100) then
			nbDone = nbDone + 1;
		end
	end
	return nbDone.."/"..#challenges;
end

local function GetChallengeScore()
	local score = 0;
	local challengesDB = core.DBchallenge.data;
	for idif = 1, #challengesDB do
		for i = 1, #challengesDB[idif] do
			local challengeTabDone = 0;
			local tabtoAvoid = {};
			local nbTab = 0;
			for z = 1, #challengesDB[idif][i].tab do
				if (challengesDB[idif][i].tab[z].name == core.L["Alliance"] or challengesDB[idif][i].tab[z].name == core.L["Horde"]) then
					local factionPlayer = UnitFactionGroup("player")
					if (factionPlayer ~= challengesDB[idif][i].tab[z].faction) then
						table.insert(tabtoAvoid, challengesDB[idif][i].tab[z].name);
					else
						nbTab = nbTab + 1;
					end
				else
					nbTab = nbTab + 1;
				end
			end
			for i2 = 1, #challengesDB[idif][i].tab do
				if (checkIfHaveName(challengesDB[idif][i].tab[i2].name, tabtoAvoid) == false) then
					local challengePageDone = 0;
					for i3 = 1, #challengesDB[idif][i].tab[i2].page do
						if (core.libs.ifDonePage(challengesDB[idif][i].tab[i2].page[i3]) == true) then
							challengePageDone = challengePageDone + 1;
						end
						if (challengePageDone == #challengesDB[idif][i].tab[i2].page) then
							challengeTabDone = challengeTabDone + 1;
						end
						if (challengeTabDone == nbTab) then
							if (idif == 1) then
								score = score + 750;
							elseif (idif == 2) then
								score = score + 500;
							elseif (idif == 3) then
								score = score + 250;
							end
						end
					end
				end
			end
		end
	end
	return score;
end

--- ===== COLLECTIONS ===== ---
local function GetCollectionScore()
	local score        = 0;
	local localization = GetLocale();
	for i = 1, #WC_ListGuides do
		local infoGuide = WC_Lib.GetGuideByID(WC_ListGuides[i], "WC");
		if (core.L["LangID"][infoGuide.lang[1]] == localization and
			WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true and
			infoGuide.av_settings.createBy == "WoW Challenger") then
			if (infoGuide.difficulty == 1) then
				score = score + 50;
			elseif (infoGuide.difficulty == 2) then
				score = score + 100;
			elseif (infoGuide.difficulty == 3) then
				score = score + 150;
			end
		end
	end
	return score;
end

local function GetNbDoneCollections(infoCollection)
	local collections = Split(infoCollection, ",");
	local nbDone      = 0;
	for i = 1, #collections do
		if (tonumber(collections[i]) == 1) then
			nbDone = nbDone + 1;
		end
	end
	return nbDone.."/"..#collections;
end

local function GetInfoCollectionsDone()
	local ret          = "";
	if (WC_ListGuides ~= 0) then
		local guidesByWC = WC_Lib.GetGuidesByWoWChallengerByLocal();
		for i = 1, #guidesByWC do
			local infoGuide = guidesByWC[i];
			if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true) then
				ret = ret.."1,";
			else
				ret = ret.."0,";
			end
		end
		ret = ret:sub(1, -2); -- enlève la virgule de fin
	end	
	return ret;
end
--- ===== END ===== ---

function WC_Lib.GetPlayerScore()
	CurrentPlayerScore = GetCampaignScore() + GetChallengeScore() + GetCollectionScore();
	return CurrentPlayerScore;
end

function WC_Lib.SetPlayerScore()
	--local CollectionScore = GetCollectionScore();
	if (#WC_ListGuides == 0) then
		_G["WC_RankingPlayerScore"]:SetText("?");
		_G["WC_RankingWarningPlayerScore"]:Show();
	else
		_G["WC_RankingPlayerScore"]:SetText(WC_Lib.GetPlayerScore());
		_G["WC_RankingWarningPlayerScore"]:Hide();
	end
end

function WC_Lib.UpdateNoTextRanking(chat)
	local value = 0;
	local id    = 0;
	if (chat == "GUILD") then
		id = 1;
		for key,data in pairs(WC_Ranking.Guild) do
			value = value + 1;
		end
	elseif (chat == "INSTANCE_CHAT" or chat == "PARTY") then
		id = 2;
		for key,data in pairs(WC_Ranking.People) do
			value = value + 1;
		end
	end
	if _G["WC_RankingNoInfoText"..id] then
		if (value == 0) then
			_G["WC_RankingNoInfoText"..id]:Show();
		else		
			_G["WC_RankingNoInfoText"..id]:Hide();
		end
	end
end

local function SortRanking(list)
	local newList = {};
	for key,data in pairs(list) do
		table.insert(newList, data);
	end
	table.sort(newList, function(a,b)  return tonumber(a[3]) > tonumber(b[3]) end);
	return newList;
end

local function valueToPercent(value)
	local new = Split(value, "/");
	return math.floor((new[1]/new[2]) * 100);
end

function WC_Lib.OnShowDetailsProfile(self)
	local DetailsFrame = _G["WC_RankingDetailsProfile"];
	
	-- UPDATE VALUES --
	DetailsFrame.title:SetText(self.name);
	
	local scoreText = core.L["Score"]..core.L["2points"].."|cffffffff"..self.score.."|r";
	if (self.supportRank > 0) then
		scoreText = scoreText.." - "..core.L["Soutien"]..core.L["2points"]..core.L["SupportList"][self.supportRank];
	end
	DetailsFrame.scoreText:SetText(scoreText);
	
	local width = valueToPercent(self.donePart[1]) * (DetailsFrame.CampaignsFrames.header:GetWidth() / 100);
	if width == 0 then
		DetailsFrame.CampaignsFrames.header.progressBg:Hide();
	else
		DetailsFrame.CampaignsFrames.header.progressBg:Show();
	end
	DetailsFrame.CampaignsFrames.header.progressBg:SetWidth(width);
	DetailsFrame.CampaignsFrames.header.progressText:SetText(self.donePart[1]);
	
	local width = valueToPercent(self.donePart[2]) * (DetailsFrame.ChallengesFrames.header:GetWidth() / 100);
	if width == 0 then
		DetailsFrame.ChallengesFrames.header.progressBg:Hide();
	else
		DetailsFrame.ChallengesFrames.header.progressBg:Show();
	end
	DetailsFrame.ChallengesFrames.header.progressBg:SetWidth(width);
	DetailsFrame.ChallengesFrames.header.progressText:SetText(self.donePart[2]);
	
	local width = valueToPercent(self.donePart[3]) * (DetailsFrame.CollectionsFrames.header:GetWidth() / 100);
	if width == 0 then
		DetailsFrame.CollectionsFrames.header.progressBg:Hide();
	else
		DetailsFrame.CollectionsFrames.header.progressBg:Show();
	end
	DetailsFrame.CollectionsFrames.header.progressBg:SetWidth(width);
	DetailsFrame.CollectionsFrames.header.progressText:SetText(self.donePart[3]);
	
	--- ===== CAMPAIGNS PART ===== ---
	local campaignDone   = tonumber(Split(self.donePart[1], "/")[1]);
	local campaignNbDone = tonumber(self.infoReceived[1]);
	local iDone        = 0;
	for i = 1, #core.DBcampaign do
		local campaigns = _G["WC_RankingIconBoss"..i];
		campaigns.comparedName  = self.name;
		campaigns.comparedValue = {};
		campaigns.yourValue     = {};
		if (iDone <= campaignDone - 1) then
			iDone = iDone + 1;
			campaigns:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/design_campaign/icon_zone"..i.."_done",
													insets = {left = -15, right = -15, top = -25, bottom = -25}})
		else
			campaigns:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/campaign/design_campaign/icon_zone"..i,
													insets = {left = -15, right = -15, top = -25, bottom = -25}})
		end
		for j = 1, #core.DBcampaign[i].fights do
			local comparedColor = "|cffffffff";
			local yourColor     = "|cffffffff";
			if (campaignNbDone > 0) then
				comparedColor = "|T236362:14|t |cff7e7e7e";
			end
			local yourCampaigns = nil;
			if i == 1 then
				yourCampaigns = Campaign1;
			elseif i == 2 then
				yourCampaigns = Campaign2;
			elseif i == 3 then
				yourCampaigns = Campaign3;
			elseif i == 4 then
				yourCampaigns = Campaign4;
			end
			if (yourCampaigns[j].done == true) then
				yourColor = "|T236362:14|t |cff7e7e7e";
			end
			local text  = core.L["Fight"].." "..j;
			if (core.DBcampaign[i].fights[j].boss == true) then
				text = text.." ("..core.L["Boss"]..")";
			end
			table.insert(campaigns.comparedValue, comparedColor..text.."|r");
			table.insert(campaigns.yourValue, yourColor..text.."|r");
			campaignNbDone = campaignNbDone - 1;
		end
	end
	
	--- ===== CHALLENGES PART ===== ---
	local challengesPourcent = Split(self.infoReceived[2], ",");
	local k = 1;
	for i = 1, #core.DBchallenge.data do
		for j = 1, #core.DBchallenge.data[i] do
			local challenge = _G["WC_RankingProgressBarChallenges"..k];
			local pourcent  = challengesPourcent[k].."%";
			challenge.progressText:SetText(pourcent);
			challenge.progressBg:SetWidth(tonumber(challengesPourcent[k]) * (challenge:GetWidth() / 100));
			challenge.comparedValue = pourcent;
			challenge.comparedName  = self.name;
			challenge.yourValue     = math.floor(core.libs.progressPourcent(core.DBchallenge.data[i][j])).."%";			
			k = k + 1;
		end
	end
	
	--- ===== COLLECTIONS PART ===== ---
	local collectionDone = Split(self.infoReceived[3], ",");
	local guidesByWC = WC_Lib.GetGuidesByWoWChallengerByLocal();
	for i = 1, #collectionDone do
		local icon = _G["WC_RankingIconCollections"..i - 1];
		if icon then
			if (collectionDone[i] and tonumber(collectionDone[i]) == 1) then
				icon.comparedValue = "|cff00ff00"..core.L["MountCollected"].."|r";
				icon.greenCheck:Show();
			else
				icon.comparedValue = "|cffff0000"..core.L["MountNotCollected"].."|r";
				icon.greenCheck:Hide();
			end
			local infoGuide = guidesByWC[i];
			if (WC_Lib.checkIfGuideIsDone(infoGuide.category, infoGuide.id, infoGuide.Model.modID) == true) then
				icon.yourValue =  "|cff00ff00"..core.L["MountCollected"].."|r";
			else
				icon.yourValue =  "|cffff0000"..core.L["MountNotCollected"].."|r";
			end
			icon.comparedName = self.name;
		end
	end	
	PlaySound("620", "sfx");
	DetailsFrame:Show();
end

function WC_Lib.UpdateRankingPortrait()
	local arrPlayersGroup = {};
	local instance        = nil;
	
	if IsInRaid() then
		instance = "raid";
		for i = 1, MAX_RAID_MEMBERS  do
			local name, realm = UnitName(instance..i);
			if not realm then
				realm = GetNormalizedRealmName();
			end
			if name and realm then
				table.insert(arrPlayersGroup, {name.."-"..realm, i });
			end
		end
	elseif IsInGroup() then	
		instance = "party";
		for i = 1, 4 do
			local name, realm = UnitName(instance..i);
			if not realm then
				realm = GetNormalizedRealmName();
			end
			if name and realm then
				table.insert(arrPlayersGroup, {name.."-"..realm, i });
			end
		end
	end
	if instance then
		-- UPDATE FOR GUILD --		
		local j = 1;
		for key,v in pairs(WC_Ranking.Guild) do		
			local playerFrame = _G["WC_RankingTableTab1ContentPlayer"..j];
			if not playerFrame then
				break;
			end
			local pos = WC_Lib.findInArray(arrPlayersGroup, playerFrame.name, 1);
			if pos ~= -1 then			
				SetPortraitTexture(playerFrame.portrait, instance..arrPlayersGroup[pos][2]);
			end
			j = j + 1;
		end
		
		local k = 1;
		-- UPDATE FOR GROUP --
		for key,v in pairs(WC_Ranking.People) do
			local playerFrame = _G["WC_RankingTableTab2ContentPlayer"..k];
			if not playerFrame then
				break;
			end
			local pos = WC_Lib.findInArray(arrPlayersGroup, playerFrame.name, 1);
			if pos ~= -1 then			
				SetPortraitTexture(playerFrame.portrait, instance..arrPlayersGroup[pos][2]);
			end			
			k = k + 1;
		end
	end
end

function WC_Lib.CreatePlayerFrameLittle(id, parent)
	local playerFrame = CreateFrame("Button", parent:GetName().."Player"..id, parent);
	playerFrame:SetSize(parent:GetWidth(), 60);
	playerFrame:SetScript("OnClick", WC_Lib.OnShowDetailsProfile);
	playerFrame:SetScript("OnLeave", function(self) 
		self.portrait.delBtn:Hide();
		WC_Lib.OnLeave();
	end);
	playerFrame:SetScript("OnEnter", WC_Lib.OnEnterRankingPlayer);
	local y = 0
	if id == 4 then y = -35 end
	playerFrame:SetPoint("TOP",  _G[parent:GetName().."Player"..id - 1], "BOTTOM", 0, y);
	
	playerFrame.bg = CreateFrame("Frame", nil, playerFrame, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.bg:SetSize(612, 90);
	playerFrame.bg:SetPoint("LEFT", playerFrame, "LEFT", -90, 0);
	playerFrame.bg:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/ranking/bgListPlayer_alone"});


	playerFrame.portrait = playerFrame:CreateTexture(nil, "BACKGROUND")
	playerFrame.portrait:SetHeight(45)
	playerFrame.portrait:SetWidth(45)
	playerFrame.portrait:SetPoint("LEFT", playerFrame, "LEFT", 20, 0);
	playerFrame.portrait:SetTexture("Interface/CHARACTERFRAME/TempPortrait", false);
	
	playerFrame.portrait.bg = CreateFrame("Frame", nil, playerFrame, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.portrait.bg:SetSize(100,100);
	playerFrame.portrait.bg:SetPoint("CENTER", playerFrame.portrait, "CENTER")
	playerFrame.portrait.bg:SetFrameLevel(playerFrame.bg:GetFrameLevel() + 1)
	playerFrame.portrait.bg:SetBackdrop({bgFile = "Interface/Addons/WoWChallenger/images/ranking/portraitPlayer"});
	
	playerFrame.portrait.iconSupport = CreateFrame("Frame", nil, playerFrame.portrait.bg, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.portrait.iconSupport:SetSize(32,32);
	playerFrame.portrait.iconSupport:SetPoint("BOTTOMLEFT", playerFrame.portrait.bg, "BOTTOMLEFT", 17, 18)
	playerFrame.portrait.iconSupport:SetBackdrop({bgFile = ""});
	
	playerFrame.portrait.delBtn = CreateFrame("Button", nil, playerFrame.portrait.bg);
	playerFrame.portrait.delBtn:SetSize(16, 16);
	playerFrame.portrait.delBtn:SetPushedTexture("Interface/Buttons/UI-GroupLoot-Pass-Up");
	playerFrame.portrait.delBtn:SetNormalTexture("Interface/Buttons/UI-GroupLoot-Pass-Down");
	playerFrame.portrait.delBtn:SetHighlightTexture("Interface/Buttons/UI-GROUPLOOT-PASS-HIGHLIGHT");
	playerFrame.portrait.delBtn:SetPoint("TOPLEFT", playerFrame.portrait.bg, "TOPLEFT", 15, -22);
	playerFrame.portrait.delBtn:SetScript("OnClick", function (self)
		WC_Ranking.Guild[self.name] = nil;
		WC_Lib.UpdateRankingList("GUILD");
	end);
	playerFrame.portrait.delBtn:Hide();
	playerFrame.portrait.delBtn:SetScript("OnEnter", function (self)
		GameTooltip:SetOwner(self, "ANCHOR_LEFT", 0, 0);
		GameTooltip:AddLine(core.L["Supprimer"]);
		GameTooltip:Show();
		self:Show();
	end);	
	playerFrame.nameText = playerFrame.bg:CreateFontString(nil, "OVERLAY", nil, playerFrame.bg);
	playerFrame.nameText:SetPoint("LEFT", playerFrame.bg, "LEFT", 165, 22);
	playerFrame.nameText:SetFontObject("GameFontHighlightSmall");
	
	playerFrame.scoreText = playerFrame.bg:CreateFontString(nil, "OVERLAY", nil, playerFrame.bg);
	playerFrame.scoreText:SetPoint("CENTER", playerFrame.bg, "CENTER", -15, -5);
	playerFrame.scoreText:SetFont(fontText, 30, "OUTLINE");
	
	playerFrame.rankText = playerFrame:CreateFontString(nil, "OVERLAY", nil, playerFrame);
	playerFrame.rankText:SetPoint("RIGHT", playerFrame, "RIGHT", -25, -3);
	playerFrame.rankText:SetFont(fontText, 40, "OUTLINE");
	playerFrame.rankText:SetText(id);
	
	return playerFrame;
end

function WC_Lib.CreatePlayerFrame(id, parent)
	local playerFrame = CreateFrame("Button", parent:GetName().."Player"..id, parent);
	playerFrame:SetSize(parent:GetWidth(), 80);
	playerFrame:SetScript("OnClick", WC_Lib.OnShowDetailsProfile);
	playerFrame:SetScript("OnLeave", function(self) 
		self.portrait.delBtn:Hide();
		WC_Lib.OnLeave();
	end);
	playerFrame:SetScript("OnEnter", WC_Lib.OnEnterRankingPlayer);
	
	playerFrame.bg = CreateFrame("Frame", nil, playerFrame, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.bg:SetSize(playerFrame:GetWidth(), 128);
	playerFrame.bg:SetPoint("LEFT", playerFrame, "LEFT", -40, 0);
	playerFrame.bg:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/ranking/bgListPlayer"});

	playerFrame.portrait = playerFrame:CreateTexture(nil, "BACKGROUND")
	playerFrame.portrait:SetHeight(60);
	playerFrame.portrait:SetWidth(60);
	playerFrame.portrait:SetPoint("LEFT", playerFrame.bg, "LEFT", 60, 0);
	playerFrame.portrait:SetTexture("Interface/CHARACTERFRAME/TempPortrait", false)
	
	playerFrame.nameText = playerFrame.bg:CreateFontString(nil, "OVERLAY", nil, playerFrame.bg);
	playerFrame.nameText:SetPoint("LEFT", playerFrame.bg, "LEFT", 125, 29);
	playerFrame.nameText:SetFontObject("GameFontHighlight");
	
	playerFrame.portrait.iconSupport = CreateFrame("Frame", nil, playerFrame.bg, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.portrait.iconSupport:SetSize(42,42);
	playerFrame.portrait.iconSupport:SetPoint("BOTTOMLEFT", playerFrame.bg, "BOTTOMLEFT", 47, 23)
	playerFrame.portrait.iconSupport:SetBackdrop({bgFile = ""});

	playerFrame.portrait.delBtn = CreateFrame("Button", nil, playerFrame.bg);
	playerFrame.portrait.delBtn:SetSize(20, 20);
	playerFrame.portrait.delBtn:SetPushedTexture("Interface/Buttons/UI-GroupLoot-Pass-Up");
	playerFrame.portrait.delBtn:SetNormalTexture("Interface/Buttons/UI-GroupLoot-Pass-Down");
	playerFrame.portrait.delBtn:SetHighlightTexture("Interface/Buttons/UI-GROUPLOOT-PASS-HIGHLIGHT");
	playerFrame.portrait.delBtn:SetPoint("TOPLEFT", playerFrame.portrait, "TOPLEFT", -12, 5);
	playerFrame.portrait.delBtn:Hide();
	playerFrame.portrait.delBtn:SetScript("OnClick", function (self)
		WC_Ranking.Guild[self.name] = nil;
		WC_Lib.UpdateRankingList("GUILD");
	end);
	playerFrame.portrait.delBtn:SetScript("OnLeave", WC_Lib.OnLeave);
	playerFrame.portrait.delBtn:SetScript("OnEnter", function (self)
		GameTooltip:SetOwner(self, "ANCHOR_LEFT", 0, 0);
		GameTooltip:AddLine(core.L["Supprimer"]);
		GameTooltip:Show();
		self:Show();
	end);
	
	playerFrame.scoreText = playerFrame.bg:CreateFontString(nil, "OVERLAY", nil, playerFrame.bg);
	playerFrame.scoreText:SetPoint("CENTER", playerFrame.bg, "CENTER", -15, -5);
	playerFrame.scoreText:SetFont(fontText, 45, "OUTLINE");
	
	playerFrame.rankFrame = CreateFrame("Frame", nil, playerFrame, BackdropTemplateMixin and "BackdropTemplate");
	playerFrame.rankFrame:SetSize(128, 128);
	playerFrame.rankFrame:SetPoint("RIGHT", playerFrame, "RIGHT", 0, 0);
	
	playerFrame.rankText = playerFrame.rankFrame:CreateFontString(nil, "OVERLAY", nil, playerFrame.rankFrame);
	playerFrame.rankText:SetPoint("CENTER", playerFrame.rankFrame, "CENTER", -5, -3);
	playerFrame.rankText:SetFont(fontText, 65, "OUTLINE");

	local rank = id;
	if (id == 1) then
		rank = "|cffffd700"..rank.."|r";
	elseif (id == 2) then	
		rank = "|cffc0c0c0"..rank.."|r";
	elseif (id == 3) then	
		rank = "|cffb08d57"..rank.."|r";
	end
	playerFrame.rankText:SetText(rank)
	
	if (id == 1) then
		playerFrame:SetPoint("TOPLEFT", parent, "TOPLEFT", 0, 0);
		playerFrame.rankFrame:SetBackdrop({bgFile = "Interface/ACHIEVEMENTFRAME/UI-Achievement-Bling"});
	else
		playerFrame:SetPoint("TOP",  _G[parent:GetName().."Player"..id - 1], "BOTTOM", 0, 0);
		playerFrame.rankFrame:SetBackdrop({bgFile = ""});
	end
	
	return playerFrame;
end

function WC_Lib.UpdateDelimiter(id, parent)
	local nameParent = parent:GetName();
	local mainFrame  = _G[nameParent.."_Delimiter"];
	if not mainFrame then
		local frame = CreateFrame("Frame", nameParent.."_Delimiter", parent, BackdropTemplateMixin and "BackdropTemplate");
		frame:SetSize(350, 32);
		frame:SetBackdrop({bgFile = "Interface/AddOns/WoWChallenger/images/ranking/delimiter"});
		frame:SetPoint("TOP", _G[nameParent.."Player"..id - 1], "BOTTOM", 0, 0);
		frame:Show();
	else
		mainFrame:Show();
	end
end

function WC_Lib.UpdateRankingList(chat)
	local frameParent = nil;
	local list        = nil;
	if (chat == "GUILD") then
		frameParent = _G["WC_RankingTableTab1Content"];
		list        = WC_Ranking.Guild;
	elseif (chat == "INSTANCE_CHAT" or chat == "PARTY") then
		frameParent = _G["WC_RankingTableTab2Content"];
		list        = WC_Ranking.People;
	end
	
	if frameParent and list then
		list             = SortRanking(list);
		local j          = 1;
		local nameParent = frameParent:GetName();
		local nbList     = #list;
		for i = 1, #list do
			local playerFrame    = _G[nameParent.."Player"..i];
			local data           = list[i];
			local name           = data[#data];
			local score          = data[3];
			local infoCampaign   = tonumber(data[4]);
			local infoChallenge  = data[5];
			local infoCollection = data[6];
			local supportRank    = tonumber(data[7]) or 0;
			
			
			---- CREATE PLAYER FRAME IF NOT EXIST ----
			if not playerFrame then
				if (i < 4) then
					playerFrame = WC_Lib.CreatePlayerFrame(i, frameParent);
				else
					if i == 4 then
						WC_Lib.UpdateDelimiter(i, frameParent);
					end
					playerFrame = WC_Lib.CreatePlayerFrameLittle(i, frameParent);
				end
			end
			
			---- VALUES ----			
			playerFrame.portrait.delBtn.name = name;
			if (name == WC_Lib.fullNamePlayer) then
				name = name.." ("..core.L["Vous"]..")";
				SetPortraitTexture(playerFrame.portrait, "player");
			else
				playerFrame.portrait:SetTexture(pathPortrait..genders[tonumber(data[1])].."-"..data[2], false);		
			end
			playerFrame.chat         = chat;
			playerFrame.name         = name;
			playerFrame.score        = score;
			playerFrame.infoReceived = {infoCampaign, infoChallenge, infoCollection};
			playerFrame.donePart     = {GetNbDoneCampaignsByCurrentLevel(infoCampaign), GetNbDoneChallenges(infoChallenge), GetNbDoneCollections(infoCollection)};
			playerFrame.supportRank  = supportRank;
			playerFrame.nameText:SetText(name);
			playerFrame.scoreText:SetText(score);
			
			if chat == "INSTANCE_CHAT" or chat == "PARTY" then
				playerFrame.portrait.delBtn:Hide();
			end

			if supportRank > 0 then
				playerFrame.portrait.iconSupport:SetBackdrop({bgFile = "Interface/PVPFrame/Icons/prestige-icon-6-"..supportRank});
			else
				playerFrame.portrait.iconSupport:SetBackdrop({bgFile = ""});
			end
			
			playerFrame:Show();			
			if (j <= MAX_NUMBER_PLAYER) then
				j = j + 1;
			end
		end
		---- HIDE LES FRAMES EN TROP ----
		for j = j, nbList + 1 do
			if (_G[nameParent.."Player"..j] == nil) then
				break;
			else
				_G[nameParent.."Player"..j]:Hide();
			end
		end
		if _G[nameParent.."_Delimiter"] and nbList < 4 then
			_G[nameParent.."_Delimiter"]:Hide();
		end
	end	
	WC_Lib.UpdateNoTextRanking(chat);
	WC_Lib.UpdateRankingPortrait();
end

-- === SEND/RECEIVE PLAYER INFO === --
function WC_Lib.SendInfoPlayer(chat)
	if (#WC_ListGuides > 0) then
		local score = CurrentPlayerScore;
		if (score == 0) then
			score = WC_Lib.GetPlayerScore();
		end
		local supportRank = 0;
		if WC_Lib.spts[WC_Lib.fullNamePlayer] then supportRank = WC_Lib.spts[WC_Lib.fullNamePlayer] end
		local _, raceFile = UnitRace("player");
		local gender      = UnitSex("player");
		local message     = gender..";"..raceFile..";"..score..";"..GetCampaignScore(true)..";"..GetInfoChallengesDone()..";"..GetInfoCollectionsDone()..";";
		message           = message..supportRank;
		
		local success = nil;
		if chat then
			success = C_ChatInfo.SendAddonMessage( "WCRanking", message, chat);
		else
			success = C_ChatInfo.SendAddonMessage( "WCRanking", message, "PARTY");
			success = C_ChatInfo.SendAddonMessage( "WCRanking", message, "INSTANCE_CHAT");
			success = C_ChatInfo.SendAddonMessage( "WCRanking", message, "GUILD");
		end
		if not success then
			print("[|c00FF7F00WC|r]: Failed to send add-on message, message rejected by the server.");
		end
	end
end

local function OnEventReceiveMessage(self, event, ...)
	local prefix, message, chat, sender = ...;
	if (prefix == "WCRanking") then
		local data = Split(message, ";");
		table.insert(data, sender);
		if (chat == "GUILD") then
			WC_Ranking.Guild[sender] = data;
		elseif (chat == "INSTANCE_CHAT" or chat == "PARTY") then
			WC_Ranking.People[sender] = data;
		end
		WC_Lib.UpdateRankingList(chat);
	end
end

local frameReceiveMessage = CreateFrame("Frame")
frameReceiveMessage:RegisterEvent("CHAT_MSG_ADDON");
frameReceiveMessage:SetScript("OnEvent", OnEventReceiveMessage)


-- === EVENT WHEN PLAYER_ENTERING_WORLD === --
local function OnEventGetInfoPlayer(self, event, ...)
	WC_Lib.fullNamePlayer = UnitName("player").."-"..GetNormalizedRealmName();
	if IsInGroup() then
		core.cpgn.WC_wait(3, WC_Lib.SendInfoPlayer, "PARTY");
	end
	if IsInRaid() then
		core.cpgn.WC_wait(3, WC_Lib.SendInfoPlayer, "INSTANCE_CHAT");
	end
	if IsInGuild() then
		core.cpgn.WC_wait(3, WC_Lib.SendInfoPlayer, "GUILD");
	end
end

local frameInfoPlayer = CreateFrame("Frame")
frameInfoPlayer:RegisterEvent("PLAYER_ENTERING_WORLD");
frameInfoPlayer:RegisterEvent("GROUP_JOINED");
frameInfoPlayer:SetScript("OnEvent", OnEventGetInfoPlayer);

C_ChatInfo.RegisterAddonMessagePrefix("WCRanking");