-- Author      : Peder
-- Create Date : 1/6/2023 12:18:44 PM

---------------------------------------------
-- Begin Document
---------------------------------------------
---------------------------------------------
-- Globals
---------------------------------------------
iStableMaster = iStableMaster or {};

function iStableMaster:InstantiatePetScrollElement(Name,index,parentName,namespace,arrName,templateInfo)
	name = Name..index;
	_G[namespace] = _G[namespace] or {};
	iStableMaster.PetScrollDefinedNameSpace = namespace or "iStableMaster";
	iStableMaster.PetScrollDefinedArrName = arrName or "ScrollFrameArrElem";
	--local function FindTemplateInfo(...) return iStableMasterStableDB.PetInfo.ActiveSlot1; end
	--iStableMaster.PetScrollDefinedInfoArray = templateInfo or (function() if(index < 6) then return iStableMasterStableDB.PetInfo["ActiveSlot"..index] else return iStableMasterStableDB.PetInfo["StableSlot"..index-5] end end);
	iStableMaster.PetScrollDefinedInfoArray = templateInfo or iStableMasterStableDB.PetInfo["ActiveSlot"..1];--- why this aka why is it active slot 1 if active slot 1 may not be in the list at all? or if it is simply hidden but still something?
	_G[namespace][arrName][name] = CreateFrame("Frame",name,_G[namespace][arrName][parentName], iStableMaster_PetScrollElementMixin and "PetScrollElementTemplate")
	-- technically this uses way more memory than needed, because we make the variable/field/property as a member for each PetFrame, instead of making it associated as an if it exist then add to a single frame, its all the same value anyway, for future optimization do this instead of what i do below here.
	_G[namespace][arrName][name].FrameFamily = Name; 
end

---------------------------------------------
-- Globals End
---------------------------------------------

---------------------------------------------
-- PetScrollFrameTemplate
---------------------------------------------
		-- For the new scrollframe

---------------------------------------------
-- PetScrollFrameTemplate end
---------------------------------------------

---------------------------------------------
-- PetScrollElementTemplates
---------------------------------------------
iStableMaster_PetScrollElementMixin = { };
function iStableMaster_PetScrollElementMixin:SetNameSpace(self,...)
	self.namespaces = {};
	
	self.namespaces.AddOnNameSpace = ... or "iStableMaster";
	self.namespaces.AddOnNameSpaceOptionsDB = self.namespaces.AddOnNameSpace.."OptionsDB";
	--print(self.namespaces.AddOnNameSpaceOptionsDB);
	--self.ScrollFrameArrElem = iStableMaster.ScrollFrameArrElem[
end
	
if(IsAddOnLoaded("ElvUI"))then
iStableMaster.ElvUI = LibStub("AceAddon-3.0"):GetAddon("ElvUI")
iStableMaster.ElvUIEngineSkinModule = iStableMaster.ElvUI:GetModule("Skins");
--iStableMaster.AS = unpack(AddOnSkins);
function iStableMaster.ElvUIEngineSkinModule:HandleiStableMasterPetButton(button)		
			button:StripTextures()
			button:CreateBackdrop("Transparent")
			button.backdrop:Point("TOPLEFT", 42, 0)
			button.backdrop:Point("BOTTOMRIGHT", 0, 1)
	        if (button.IsEnabled == nil) then
			function button:IsEnabled() return true end;
	        end 
			--print(button:GetParent():GetName());
			
			--button:HookScript('OnEnter', function(s) s:SetBackdropBorderColor(unpack(iStableMaster.AS.Color)) end)
			--button:HookScript('OnLeave', function(s) s:SetBackdropBorderColor(unpack(iStableMaster.AS.BorderColor)) end)
			
			button:HookScript("OnMouseDown",
				
				function(self)
					local AddOnNameSpace = self:GetParent().namespaces.AddOnNameSpace;
					local ImplementationArr = self:GetParent().ImplementationArr;
					local name = self:GetParent():GetName();
					local s = self:GetParent();
					self.backdrop:SetBackdropBorderColor(1,1,1,1);
					
					if _G[AddOnNameSpace].previouslySelected ~= nil then
						--print(AddOnNameSpace,ImplementationArr,tostring(_G[AddOnNameSpace].previouslySelected))
					iStableMaster.ElvUIEngineSkinModule.SetOriginalBackdrop(_G[AddOnNameSpace][ImplementationArr][s.FrameFamily..tostring(_G[AddOnNameSpace].previouslySelected)].layerwrapper);
					--iStableMaster.ElvUIEngineSkinModule.SetOriginalBackdrop(_G[AddOnNameSpace][ImplementationArr][tostring(name:gsub(tostring(s.info.Slot), ""))..tostring(_G[AddOnNameSpace].previouslySelected)].layerwrapper);
					end
					--print(tostring(name:gsub(tostring(s.info.Slot), "")),self:GetParent().info.Slot);
					--button.isSelected = self:GetParent().info.Slot == iStableMaster.currentlyActiveHighlight
				end)
			--iStableMaster.ElvUIEngineSkinModule.SetModifiedBackdrop(self) 
			
		button:HookScript("OnEnter", function(self) iStableMaster.previouslySelected = iStableMaster.currentlyActiveHighlight; if(self.selected:GetAlpha() == 1)	then self.backdrop:SetBackdropBorderColor(1,1,1,1); else iStableMaster.ElvUIEngineSkinModule.SetModifiedBackdrop(self) end end);
			button:HookScript("OnLeave", 
					function(self)
						if(self.selected:GetAlpha() == 1)	then
							self.backdrop:SetBackdropBorderColor(1,1,0,1);
						else
							iStableMaster.ElvUIEngineSkinModule.SetOriginalBackdrop(self) 
						end
					end)
					--end end)
			button.isSkinned = true;
end

end

function iStableMaster_PetScrollElementMixin:SetName(input) self.layerwrapper.name:SetText(input) end;
function iStableMaster_PetScrollElementMixin:SetSpecIcon(input) iStableMaster:SetSpecIconOnScrollElement(input,self.layerwrapper.SpecIconWrapper.intrinsic1) end;
function iStableMaster_PetScrollElementMixin:SetPetIcon(input) if(input ~= nil and input ~= "N/A") then self.layerwrapper.PetIcon.PetIconFrame.PetIconTexture:SetTexture(input); else self.layerwrapper.PetIcon.PetIconFrame.PetIconTexture:SetAtlas("ui-hud-actionbar-iconframe-slot");  end end;
function iStableMaster_PetScrollElementMixin:UpdatePetIcon(input) f:SetPetIcon(root.info.icon); end;
function iStableMaster_PetScrollElementMixin:UpdateSelected(input) if(self.info.Slot == input) then self.layerwrapper.selected:SetAlpha(1) else self.layerwrapper.selected:SetAlpha(0) end end
function iStableMaster_PetScrollElementMixin:UpdateFavStatus(input) iStableMaster:UpdateFavStar(input,self.layerwrapper.PetIcon.FavStar) end;
function iStableMaster_PetScrollElementMixin:SetNameWidth(input) iStableMaster:SetNameWidthPetScrollFrameElement(input,self.layerwrapper) end
function iStableMaster_PetScrollElementMixin:UpdateExoticBgPetScrollFrameColoring(self)

	if(iStableMaster:IsExotic(self.info.family)) then
		self.layerwrapper.bg:SetVertexColor(iStableMaster:GetDBColour("Default","ExoticTint"));
		self.layerwrapper.PetIcon.BorderFrame.PetIconBorder:SetVertexColor(iStableMaster:GetDBColour("Default","ExoticTint"));
	elseif (self.info.Slot <= 5) then
		self.layerwrapper.bg:SetVertexColor(iStableMaster:GetDBColour("Default","ActiveSlotTint"));
		self.layerwrapper.PetIcon.BorderFrame.PetIconBorder:SetVertexColor(iStableMaster:GetDBColour("Default","ActiveSlotTint"));
	elseif (self.info.Slot == 6 and iStableMaster.GlobalSpecialization == "Beast Mastery") then
		self.layerwrapper.bg:SetVertexColor(iStableMaster:GetDBColour("Default","AnimalCompanionTint"));
		self.layerwrapper.PetIcon.BorderFrame.PetIconBorder:SetVertexColor(iStableMaster:GetDBColour("Default","AnimalCompanionTint"));

	end
end

function iStableMaster:DefaultPetScrollElementTemplate_OnLoadInitialize()


end
function iStableMaster:DefaultPetScrollElementTemplate_OnLoadComplete() end


function iStableMaster_PetScrollFrameTemplates_PetScrollElementTemplate_OnUpdate(self)
	if(_G[self.namespaces.AddOnNameSpaceOptionsDB].PetScrollTemplateBgTint == "Default" or nil )then
	  self:UpdateExoticBgPetScrollFrameColoring(self);
	elseif(_G[self.namespaces.AddOnNameSpaceOptionsDB].PetScrollTemplateBgTint == "None") then
		-- does nothing here.
	else
		self:UpdateExoticBgPetScrollFrameColoring(self);
	end
	self:UpdateSelected(_G[self.namespaces.AddOnNameSpace].currentlyActiveHighlight)
end


---- Ancestors
-- Base
function iStableMaster:PetScrollElementBaseTemplate_OnLoadInitialize(self)
	self.bg:SetAtlas("PetList-ButtonBackground");

end
function iStableMaster_PetScrollFrameTemplates_PetScrollElementBaseTemplate_OnMouseDown(self,button)
	iStableMaster:PetCardSelect(self:GetParent());
	iStableMaster:SetSelectedHighlight();
	iStableMaster_PetScrollElementMixin:RegisterOnDragMouseDown(self, button)
end
function iStableMaster_PetScrollFrameTemplates_PetScrollElementBaseTemplate_OnUpdate(self)
iStableMaster_PetScrollElementMixin:OnDragStateUpdate(self:GetParent())
end
function iStableMaster_PetScrollFrameTemplates_PetScrollElementBaseTemplate_OnEnter(self)
	local AddOnNameSpace = self:GetParent().namespaces.AddOnNameSpace;
	self.highlight:SetAlpha(1);
	_G[AddOnNameSpace].currentHover = tonumber(self:GetParent().info.Slot);
	_G[AddOnNameSpace]:PetMouseOver(self:GetParent(),self.highlight,false);

end
function iStableMaster_PetScrollFrameTemplates_PetScrollElementBaseTemplate_OnLeave(self)
	local AddOnNameSpace = self:GetParent().namespaces.AddOnNameSpace;
	self.highlight:SetAlpha(0);
	_G[AddOnNameSpace].currentHover = tonumber(self:GetParent().info.Slot);
	_G[AddOnNameSpace]:PetMouseOver(self:GetParent(),self.highlight,true);

end
function iStableMaster_PetScrollFrameTemplates_PetScrollElementBaseTemplate_OnMouseUp(self,button)
iStableMaster_PetScrollElementMixin:RegisterOnDragMouseUp(self, button)
end

function iStableMaster_PetScrollElementMixin:RegisterOnDragMouseDown(self, button)
		local s = self:GetParent();
		local i = self:GetParent().info.Slot;
		
		if(button == "RightButton" and _G[s.namespaces.AddOnNameSpace].clickedScrollFrame ~= nil) then
			--print("I was right"); -- should automatically stable a pet to the first available slot
		end
		if button == "LeftButton" and not s.isMoving then																	 
			mousePos = {x=0,y=0}
			mousePos.x, mousePos.y = GetCursorPosition();
			s.isLeftButtonDown = true;
			_G[s.namespaces.AddOnNameSpace].clickedScrollFrame = tonumber(i);
		end
end
function iStableMaster_PetScrollElementMixin:OnDragStateUpdate(self)
		
		local i = self.info.Slot;
		if(self.tick == nil) then
			self.tick = 0;
			self.tickrate = 4;
		end
		if(math.fmod(self.tick,self.tickrate) == 0) then
			--s:UpdateSelected(iStableMaster.currentlyActiveHighlight);
			if(_G[self.namespaces.AddOnNameSpace].clickedScrollFrame ~= nil) then
				local mousePosTemp = {X=0,Y=0};
				mousePosTemp.X, mousePosTemp.Y = GetCursorPosition();
				if(mousePos.x == nil or mousePos.y == nil) then
					return;
				end;
				--print(math.floor(mousePos.x*10000),math.floor(mousePosTempX*10000),math.floor(mousePos.y*10000), math.floor(mousePosTempY*10000))
				if ((abs(math.floor(mousePos.x) - math.floor(mousePosTemp.X)) > 10) or (abs(math.floor(mousePos.y) - math.floor(mousePosTemp.Y)) > 10)) then
					--print(mousePos.x, mousePos.y, mousePosTempX, mousePosTempY);
					_G[self.namespaces.AddOnNameSpace][self.ImplementationArr][self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame].cursorMoved = true;
					--print("GUT");
					mousePos.x, mousePos.y = mousePosTemp.X, mousePosTemp.Y;
				else
					--if(math.fmod(s.tick,s.tickrate) > 4) then
					--print(self.FrameFamily,tostring(i),self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame);
					_G[self.namespaces.AddOnNameSpace][self.ImplementationArr][self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame].cursorMoved = false;
					--print("BAD!");
					--end
				end
				--print(mousePos.x.." - "..mousePos.y);
				--print(mousePosTempX, mousePosTempY);
				if(_G[self.namespaces.AddOnNameSpace][self.ImplementationArr][self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame].isLeftButtonDown and
					_G[self.namespaces.AddOnNameSpace][self.ImplementationArr][self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame].cursorMoved and 
						_G[self.namespaces.AddOnNameSpace].clickedScrollFrame ~= nil and 
							_G[self.namespaces.AddOnNameSpace][self.ImplementationArr][self.FrameFamily.._G[self.namespaces.AddOnNameSpace].clickedScrollFrame].isMoving ~= true ) then
								--- i should fix the line below to make it anonymous
								iStableMaster:PetOnDrag(iStableMaster.ScrollFrameArrElem["ScrollElementChild"..iStableMaster.clickedScrollFrame]["PetInfo"]["Slot"]);
								iStableMaster:ShowEmptyStableSlotsOnDragOnly(true,"Down");
								iStableMaster:TempHideFiltersAndSorts();
								iStableMaster.ScrollFrameArrElem[self.FrameFamily..iStableMaster.clickedScrollFrame].isMoving = true;
								--print("GUD");
							end		
				
			end
		end
		--print(s.cursorMoved);
		self.tick = self.tick+1;



end
function iStableMaster_PetScrollElementMixin:RegisterOnDragMouseUp(self, button)
		
		local s = self:GetParent();
		local i = s.info.Slot;
		--print(s.ImplementationArr,tostring(s:GetName():gsub(tostring(i), "")),s.namespaces.AddOnNameSpace);
		if(_G[s.namespaces.AddOnNameSpace].clickedScrollFrame == nil) then
			_G[s.namespaces.AddOnNameSpace]:ShowEmptyStableSlotsOnDragOnly(true,"Up");
			_G[s.namespaces.AddOnNameSpace]:TempHideFiltersAndSortsEnd();
			_G[s.namespaces.AddOnNameSpace]:SubmitSearch(_G["StablesLeftColumnEditBox"]);
			s.isLeftButtonDown = false;	
			s.isMoving = false;
		else		-- [s:GetName():sub(1, -2)..iStableMaster.clickedScrollFrame] iStableMaster.ScrollFrameArrElem["ScrollElement"..iStableMaster.clickedScrollFrame]
			--print(_G[self.namespace][self.ImplementationArr][tostring(self:GetName():gsub(tostring(i), ""))..iStableMaster.clickedScrollFrame].info.name, iStableMaster.clickedScrollFrame, tostring(self:GetName():gsub(tostring(i), ""))..iStableMaster.clickedScrollFrame);
			
			if button == "LeftButton" and _G[s.namespaces.AddOnNameSpace][s.ImplementationArr][s.FrameFamily.._G[s.namespaces.AddOnNameSpace].clickedScrollFrame].isMoving then
			--if button == "LeftButton" and _G[s.namespaces.AddOnNameSpace][s.ImplementationArr][tostring(s:GetName():gsub(tostring(i), "")).._G[s.namespaces.AddOnNameSpace].clickedScrollFrame].isMoving then
				if(_G[s.namespaces.AddOnNameSpace].clickedScrollFrame ~= nil) then
					local slot = s:GetName();
					if(_G[s.namespaces.AddOnNameSpace].currentHover ~= nil) then
						_G[s.namespaces.AddOnNameSpace]:PetOnDrop(_G[s.namespaces.AddOnNameSpace].currentHover);
					else
						ClearCursor();
					end
					_G[s.namespaces.AddOnNameSpace][s.ImplementationArr][s.FrameFamily.._G[s.namespaces.AddOnNameSpace].clickedScrollFrame].isLeftButtonDown = false;																		
					_G[s.namespaces.AddOnNameSpace][s.ImplementationArr][s.FrameFamily.._G[s.namespaces.AddOnNameSpace].clickedScrollFrame].isMoving = false;
					_G[s.namespaces.AddOnNameSpace].clickedScrollFrame = nil;
					--_G[s.namespaces.AddOnNameSpace]:ShowEmptyStableSlotsOnDragOnly(true,"Up");	--- i dont need this line and it kinda fucked with the submit search when it came after that line.
					_G[s.namespaces.AddOnNameSpace]:TempHideFiltersAndSortsEnd();
					_G[s.namespaces.AddOnNameSpace]:SubmitSearch(_G["StablesLeftColumnEditBox"]);
				end
			else
				ClearCursor();
			end
		end
		_G[s.namespaces.AddOnNameSpace].clickedScrollFrame = nil;
		_G[s.namespaces.AddOnNameSpace].clickedCardSocket = nil;
	end



function iStableMaster:PetScrollElementBaseTemplate_OnLoadComplete(self)
		
end
-- Base end
-- elements

function iStableMaster:SpecIconIntrinsicPostLoad(self)
	
	local root = self:GetParent():GetParent():GetParent();
	--print(root:GetName());
	--print(root.info.slot);
	
	--iStableMaster:Print(select(5,GetStablePetInfo(self:GetParent():GetParent():GetParent().info.slot)));
	
	root.info.specindexName = select(5,GetStablePetInfo(root.info.Slot));

	root.info.specIndex = 0;
	if(root.info.specindexName == "Ferocity") then
		root.info.specIndex = 1;
	elseif(root.info.specindexName == "Tenacity") then
		root.info.specIndex = 2;
	elseif(root.info.specindexName == "Cunning") then
		root.info.specIndex = 3;
	end
	--print(root.info.specIndex);
	
	local id, name, description, icon, background, role = GetSpecializationInfo(root.info.specIndex, false , true);

	--print(icon);
	self.SpecIcon:SetPoint("RIGHT", root, "RIGHT", 0, 0)
	self.SpecIcon:SetSize(44,44);

	self.SpecIcon:SetTexture(icon);
	self.SpecIcon:SetBlendMode("ADD");
	self.SpecIcon:SetAlpha(0.8);
	self.SpecIcon:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
	
end



---- Ancestors End
--- META FUNCTIONS
function iStableMaster:SetSpecIconOnScrollElement(specName,self) 
	local specIndex = 0;
	if(specName == "Ferocity") then
		specIndex = 1;
	elseif(specName == "Tenacity") then
		specIndex = 2;
	elseif(specName == "Cunning") then
		specIndex = 3;
	end
	--print(root.info.specIndex);
	
	local id, name, description, icon, background, role = GetSpecializationInfo(specIndex, false , true);

	--print(icon);
	--self.SpecIcon:SetPoint("RIGHT", root, "RIGHT", 0, 0)
	self.SpecIcon:SetSize(44,44);

	self.SpecIcon:SetTexture(icon);
	self.SpecIcon:SetBlendMode("ADD");
	self.SpecIcon:SetAlpha(0.8);
	self.SpecIcon:SetMask("Interface\\PETBATTLES\\PetBattle-SelectedPetGlow");
	if(icon == nil or specIndex == 0) then
		self.SpecIcon:SetAlpha(0);
	end

end

function iStableMaster:UpdateFavStar(input,frame)

	if(not input) then
		frame.bg:SetAlpha(0.2);
		frame.bg:SetVertexColor(0.953,0.953,0.953,0.2);
		frame.fill:SetAlpha(0);
		frame.frame:SetAlpha(0.75);
	else
		frame.fill:SetVertexColor(0.753,0.753,0,1);
		frame.fill:SetAlpha(1);
		frame.bg:SetAlpha(0);
		frame.frame:SetAlpha(1);

	end

end
function iStableMaster:HookedFavBgTintUpdate(self)
		
	if(not iStableMaster:IsExotic(self.info.family) and self.info.favourite and self.info.Slot ~= 6) then
		self.layerwrapper.bg:SetVertexColor(iStableMaster:GetDBColour("Default","FavouriteYellowTint"));
		self.layerwrapper.PetIcon.BorderFrame.PetIconBorder:SetVertexColor(iStableMaster:GetDBColour("Default","FavouriteYellowTint"));
	elseif(not iStableMaster:IsExotic(self.info.family) and (not self.info.favourite) and self.info.Slot ~= 6) then
		self.layerwrapper.bg:SetVertexColor(1,1,1,1);
		self.layerwrapper.PetIcon.BorderFrame.PetIconBorder:SetVertexColor(1,1,1,1);		
	end

end


function iStableMaster:SetNameWidthPetScrollFrameElement(input,wrapper) 
	local newWidth = (input - select(4,wrapper.name:GetPoint(1)));
	wrapper.name:SetWidth(newWidth);
end

--- META FUNCTIONS END

---------------------------------------------
-- PetScrollElementTemplates end
---------------------------------------------


---------------------------------------------
-- End Document
---------------------------------------------
