local _, core         = ...;
local AceSerializer   = LibStub("AceSerializer-3.0");
local AllGuidesLoaded = false;

function WC_Lib.checkIfGuideIsDone(categoryGuide, id, modID)
	local completed = false;
	if (categoryGuide == "hf") then
		if (id ~= nil and id ~= "") then
			local info = {GetAchievementInfo(tonumber(id))};
			if (info[4] ~= nil) then
				completed = info[4];
			end
		end
	elseif (categoryGuide == "mounts") then
		if (id ~= "" and id ~= nil) then
			local info = {C_MountJournal.GetMountInfoByID(id)};
			if (info[11] ~= nil) then
				completed = info[11];
			end
		end
	elseif (categoryGuide == "pets") then
		if (id ~= "" and id ~= nil) then
			local info = WC_Lib.getPetInfoById(id);
			if (info[3] ~= nil) then
				completed = info[3];
			end
		end
	elseif (categoryGuide == "transmogs") then
		if (id ~= "" and id ~= nil and modID ~= "" and modID ~= nil) then
			completed = C_TransmogCollection.PlayerHasTransmog(id , modID);
		end
	end
	return completed;
end

local function AddGuidesInAlphabeticOrder()
	local guidesName = {};
	
	for i = 1, #WC_Guides do
		table.insert(guidesName, {WC_Guides[i].info[1], WC_Guides[i].idGuide});
	end

	table.sort(guidesName, function (a, b)
		return a[1]:upper():gsub("[%z\1-\127\194-\244][\128-\191]*", WC_Lib.structures.tableAccents) < b[1]:upper():gsub("[%z\1-\127\194-\244][\128-\191]*", WC_Lib.structures.tableAccents)
	end);
	
	WC_ListGuides = {};
	for i = 1, #guidesName do
		table.insert(WC_ListGuides, guidesName[i][2])
	end
end

----- IMPORT FUNCTIONS -----
local function OnImportGuide(guide, bReplace)
	if (bReplace ~= nil and bReplace == true) then
		for i = 1, #WC_Guides do
			if (guide.idGuide == WC_Guides[i].idGuide) then
				WC_Guides[i] = guide;
				WC_Lib.AddingInEventRefresh({guide.idGuide, guide.category, guide.id, guide.Model.modID});
				g_guideSelected["WC"] = "";
				break;
			end
		end
	else
		table.insert(WC_Guides, guide);
	end
	AddGuidesInAlphabeticOrder();
	if (AllGuidesLoaded == true) then
		WC_Lib.RefreshListCollections("WC");
		_G["WC_GuidesCollection"..guide.idGuide.."_Btn"]:Click();
	end
	PlaySound("39673", "sfx");
end

local function checkSameVersion(guide)
	local guideInDB = WC_Lib.GetGuideByID(guide.idGuide, "WC");
	if (guideInDB ~= nil and guide.av_settings.version == guideInDB.av_settings.version) then
		return true;
	else
		return false;
	end
end

local function checkSameGuide(guide)
	for i = 1, #WC_ListGuides do
		if (guide.idGuide == WC_ListGuides[i]) then
			return true;
		end
	end
	return false;
end

local function checkingImportGuide(guide)
	if (checkSameGuide(guide) == true) then
		if (checkSameVersion(guide) == true) then
			local dialogSameGuideSameVersion = StaticPopup_Show("WC_ConfirmDialog", core.L["Vous possedez déjà ce guide avec la même version"]..core.L["2points"].."|cFFF5CC00"..guide["info"][1].."|r (|cFFF5CC00v"..guide.av_settings.version.."|r).\n"..core.L["Importer"].."?");
			dialogSameGuideSameVersion.func = function() OnImportGuide(guide, true); end
		else
			local guideInDB = WC_Lib.GetGuideByID(guide.idGuide, "WC");
			local dialogSameGuideDiffVersion = StaticPopup_Show("WC_ConfirmDialog", core.L["Vous possedez déjà ce guide mais avec une version différente"]..core.L["2points"].."|cFFF5CC00"..guide["info"][1].."|r (|cFFF5CC00v"..guide.av_settings.version.."|r) - |cFFF5CC00"..guideInDB["info"][1].."|r (|cFFF5CC00v"..guideInDB.av_settings.version.."|r) ("..core.L["possédé"]..").\n"..core.L["Importer"].."?");
			dialogSameGuideDiffVersion.func = function() OnImportGuide(guide, true); end
		end
		return false;
	end
	return true;
end

function WC_Lib.BeforeImportGuide(strGuide)
	strGuide                = WC_Lib.TransformEnterLetter(strGuide, false);
	local bGood, arrayGuide = AceSerializer:Deserialize(strGuide);
	if (bGood == true) then
		if (checkingImportGuide(arrayGuide) == true) then
			OnImportGuide(arrayGuide, false);
		end
	else
		UIErrorsFrame:AddMessage(core.L["Impossible d'importer : erreur de désérialisation."], 1, 0, 0);
		PlaySound("47355", "sfx", true);
	end
end

local function LoadAllGuides()
	local localization = GetLocale();
	for i = 1, #WC_Lib.guides do
		local localizGuide = WC_Lib.guides[i][localization];
		if (localizGuide ~= nil) then
			local strGuide          = WC_Lib.TransformEnterLetter(localizGuide, false);
			local bGood, arrayGuide = AceSerializer:Deserialize(strGuide);
			if (bGood == true) then
				local bStatus = 0; -- 0: Pas de guide présent; 1: Même guide présent; 2: Même guide + même version
				if (checkSameGuide(arrayGuide) == true) then
					bStatus = 1;
					if (checkSameVersion(arrayGuide) == true) then
						bStatus = 2;
					end
				end
				if (bStatus == 0) then
					OnImportGuide(arrayGuide, false);
				elseif (bStatus == 1) then
					OnImportGuide(arrayGuide, true);
				end
			else
				return false;
			end
		end
	end
	WC_Lib.RefreshListCollections("WC");
	return true;
end

--- NEW COLLECTIONS ---
local function ShowPopupImportGuide(idGuide, addon)
	if (_G["WC_PopupImportGuide"] == nil) then
		local PopupImport = CreateFrame("Frame", "WC_PopupImportGuide", UIParent, BackdropTemplateMixin and "BackdropTemplate");
		PopupImport:SetSize(550, 350);
		PopupImport:SetFrameLevel(519);
		PopupImport:SetMovable(true);
		PopupImport:EnableMouse(true);
		PopupImport:RegisterForDrag("LeftButton");
		PopupImport:SetScript("OnDragStart", PopupImport.StartMoving);
		PopupImport:SetScript("OnDragStop", PopupImport.StopMovingOrSizing);
		PopupImport:SetPoint("CENTER", UIParent, "CENTER");
		PopupImport:SetBackdrop({bgFile = "Interface/Collections/CollectionsBackgroundTile",
								edgeFile = "Interface/FriendsFrame/UI-Toast-Border",
								edgeSize = 16,
								insets = { left = 7, right = 5, top = 5, bottom = 6 }});
								
		PopupImport.close = CreateFrame("Button", nil, PopupImport, "UIPanelCloseButton");
		PopupImport.close:SetSize(32, 32);
		PopupImport.close:SetPoint("TOPRIGHT", PopupImport, "TOPRIGHT", -5, -5);
		PopupImport.close:SetScript("OnClick", function(self)
			PopupImport:Hide();
			PlaySound("854", "sfx");
		end);
		
		PopupImport.title = PopupImport:CreateFontString(nil, "OVERLAY", PopupImport);
		PopupImport.title:SetFontObject("GameFontHighlightLarge");
		PopupImport.title:SetText(core.L["Importer guide"]);
		PopupImport.title:SetSize(PopupImport:GetWidth(), 0);
		PopupImport.title:SetPoint("TOP", PopupImport, "TOP", 0, -13);

		
		PopupImport.editBox = CreateFrame("Button", nil, PopupImport, BackdropTemplateMixin and "BackdropTemplate");
		PopupImport.editBox:SetSize(460, 225);
		PopupImport.editBox:SetPoint("BOTTOM", PopupImport, "BOTTOM", 0, 40);
		PopupImport.editBox:SetScript("OnClick", function(self) self.multiline:SetFocus() end);
		PopupImport.editBox:SetBackdrop({bgFile = [[Interface\GLUES\COMMON\Glue-Tooltip-Background]],
								edgeFile = [[Interface\GLUES\COMMON\TextPanel-Border]],
								edgeSize = 14,
								insets = {left = 5, right = 1, top = 1, bottom = 4},
													});
													
		PopupImport.text = PopupImport:CreateFontString(nil, "OVERLAY", PopupImport);
		PopupImport.text:SetFontObject("GameFontNormal");
		PopupImport.text:SetText(core.L["Collez ci-dessous le code d'un guide. Veuillez à toujours faire attention à ce que vous importez."]);
		PopupImport.text:SetSize(PopupImport.editBox:GetWidth(), 0);
		PopupImport.text:SetPoint("BOTTOMLEFT", PopupImport.editBox, "TOPLEFT", 0, 15);
		
		local scroll = CreateFrame("ScrollFrame", nil, PopupImport.editBox, "UIPanelScrollFrameTemplate");
		scroll:SetSize(PopupImport.editBox:GetWidth()-20, PopupImport.editBox:GetHeight()-15);
		scroll:SetPoint("CENTER", PopupImport.editBox, "CENTER", -4, 0);
		
		PopupImport.editBox.multiline = CreateFrame("EditBox", nil, editBox);
		PopupImport.editBox.multiline:SetMultiLine(true);
		PopupImport.editBox.multiline:SetAutoFocus(true);
		PopupImport.editBox.multiline:SetFontObject("GameFontWhite");
		PopupImport.editBox.multiline:SetWidth(435);
		PopupImport.editBox.multiline:SetScript("OnTextChanged", function(self)
			if (self:GetText() == "") then
				PopupImport.BtnGoImportGuide:Disable();
			else
				PopupImport.BtnGoImportGuide:Enable();
			end
		end);
		
		scroll:SetScrollChild(PopupImport.editBox.multiline);
		
		PopupImport.BtnGoImportGuide = CreateFrame("Button", nil, PopupImport, "UIPanelButtonTemplate");
		PopupImport.BtnGoImportGuide:SetSize(150, 25);
		PopupImport.BtnGoImportGuide:SetText(core.L["Importer guide"]);
		PopupImport.BtnGoImportGuide:SetPoint("TOP", PopupImport.editBox, "BOTTOM", 0, -5);
		PopupImport.BtnGoImportGuide:Disable();
		PopupImport.BtnGoImportGuide:SetScript("OnClick", function(self)
			WC_Lib.BeforeImportGuide(PopupImport.editBox.multiline:GetText())
			_G["WC_PopupImportGuide"]:Hide();
		end);
	end
	_G["WC_PopupImportGuide"].editBox.multiline:SetText("");
	_G["WC_PopupImportGuide"]:Show();
	PlaySound("681", "sfx");
end

function WC_Lib.CreateCollectionsTab(frameParent)	
	local bgTab = CreateFrame("Frame", "WoWChallengerFrameCollections", frameParent, BackdropTemplateMixin and "BackdropTemplate");
	bgTab:SetSize(800,450);
	bgTab:SetPoint("CENTER", frameParent, "CENTER")
	bgTab:SetBackdrop({bgFile = "Interface/TALENTFRAME/spec-paper-bg",
							edgeFile = "", 
							tile = false, edgeSize = 16,
							insets = { left = 243, right = -169, top = 0, bottom = -75 }});
	local BtnLoadGuides = CreateFrame("Button", "WC_BtnLoadGuides", bgTab, "UIPanelButtonTemplate");
	BtnLoadGuides:SetSize(200, 30);
	BtnLoadGuides:SetText(core.L["Charger les guides"]);
	BtnLoadGuides:SetPoint("RIGHT", bgTab, "RIGHT", -175, 0);
	BtnLoadGuides:SetScript("OnClick", function(self)
		self:Disable();
		self:SetText(core.L["Chargement..."]);
		if (LoadAllGuides() == true) then
			self:Hide();
			_G["FrameBlockGuideList"]:Hide();
			AllGuidesLoaded = true;
		else
			PlaySound("47355", "sfx", true);
			UIErrorsFrame:AddMessage(core.L["Erreur lors du chargement des guides."], 1, 0, 0);
			self:Enable();
			self:SetText(core.L["Charger les guides"]);
		end
	end);
	
	local GuidesList = CreateFrame("Frame", "WC_GuidesList", bgTab, BackdropTemplateMixin and "BackdropTemplate");
	GuidesList:SetSize(245,450);
	GuidesList:SetPoint("LEFT", bgTab, "LEFT", 1, 0);
	GuidesList:SetBackdrop({bgFile = "Interface/FrameGeneral/UI-Background-Marble",
						edgeFile = "Interface/Tooltips/UI-Tooltip-Border", 
						tile = false, edgeSize = 16, 
						insets = { left = 0, right = 3, top = 0, bottom = 0 }});
	local HeaderGuidesList = WC_Lib.CreateHeaderGuideList(GuidesList, "WC");

	GuidesList.ScrollFrame = CreateFrame("ScrollFrame", "WC_GuidesListScroll", GuidesList, "UIPanelScrollFrameTemplate");
	GuidesList.ScrollFrame:SetPoint("TOPLEFT", GuidesList, "TOPLEFT", 0, -80);
	GuidesList.ScrollFrame:SetPoint("BOTTOMRIGHT", GuidesList, "BOTTOMRIGHT", 0, 0);
	GuidesList.ScrollFrame:SetClipsChildren(true);
	GuidesList.ScrollFrame.ScrollBar:ClearAllPoints();
	GuidesList.ScrollFrame.ScrollBar:SetPoint("TOPRIGHT", GuidesList.ScrollFrame, "TOPRIGHT", -4, -20);
	GuidesList.ScrollFrame.ScrollBar:SetPoint("BOTTOMRIGHT", GuidesList.ScrollFrame, "BOTTOMRIGHT", -4, 20);
	local child = CreateFrame("Frame", "WC_GuidesListScrollChild", GuidesList.ScrollFrame);
	child:SetSize(GuidesList:GetWidth(), GuidesList:GetWidth());

							
	GuidesList.ScrollFrame:SetScrollChild(child);
	GuidesList.ScrollFrame:SetScript("OnMouseWheel", WC_Lib.ScrollFrame_OnMouseWheel);
	
	local FrameBlockGuideList = CreateFrame("Frame", "FrameBlockGuideList", GuidesList, BackdropTemplateMixin and "BackdropTemplate");
	FrameBlockGuideList:SetSize(GuidesList:GetWidth(),GuidesList:GetHeight());
	FrameBlockGuideList:SetPoint("CENTER");
	FrameBlockGuideList:SetFrameLevel(HeaderGuidesList:GetFrameLevel() + 5);
	FrameBlockGuideList:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background"})
	FrameBlockGuideList:SetBackdropColor(0, 0, 0, 0.75);
	FrameBlockGuideList:EnableMouse(true);
	
	----- BUTTON IMPORT GUIDE -----
	local BtnImportGuide = CreateFrame("Button", "BtnImportGuide", GuidesList, "UIPanelButtonTemplate");
	BtnImportGuide:SetSize(GuidesList:GetWidth()-5, 33);
	BtnImportGuide:SetText(core.L["Importer guide"]);
	BtnImportGuide:SetPoint("TOP", HeaderGuidesList, "BOTTOM", 0, 10);
	BtnImportGuide:SetFrameLevel(HeaderGuidesList:GetFrameLevel() + 1);
	BtnImportGuide:SetScript("OnClick", ShowPopupImportGuide);
end