
local lastLinkerID = 0;

function GHU_Links(_clickFunc,_recieveLinkCallbackFunc) 
  local class = Class("GHU_Links",parent)
  
  local supportedEvents = {};
  
  local clickFunc = _clickFunc;
	local linkerRef;
	local registeredFrames = {};
 
 	local sendLinks,notLinks = {},{}; -- arrays for the link texts that have been send and the text with [ ] which is not a link
 	
  -- ======================== local functions (only available inside the class) ========================
  SearchStringForChar = function(str,char,offset)
		if not(offset) then 
			offset = 1;
		end
		for i = offset,strlen(str) do
			if strbyte(strsub(str,i,i)) == char then
				return i;
			end
		end	
	end

 
  
  -- ======================== external functions (available outside the class) ========================
  class.GenerateLink = function(self,linkRef,text,r,g,b)
    assert(type(linkRef)=="string" and type(text)=="string" and type(r) == "number" and type(b)=="number" and type(g)=="number","Incorrect input to GenerateLink(string,string,number,number,number)");
		link = "|CFF" ..string.format("%.2x",r*255) .. string.format("%.2x",g*255) .. string.format("%.2x",b*255) .."|H"..linkerRef..":"..linkRef..":0:0:0:0:0:0:0|h["..text.."]|h|r"
        return link
  end
   
  -- ======================== Hooks ========================
  
  -- outgoing links
	local orig_SendChatMessage = SendChatMessage;
	SendChatMessage = function(text,...)
		-- remove eventual links from the text. Remove only links with the same linkerRef in link as the Class
		
		-- I recommand using regular expressions (with gsub) to filter the links away
		
		-- insert all links into sendLinks
			--=from old class.Removelinks in this file
		local a,b,c,d,e,f;
		a = 0;
		while a do
			--GHU_Message("A");
			a = class.SearchStringForChar(text,91,a+1);
			b = strfind(text,"]",a);
			if not(a == nil) and b then 
				c = strbyte(text,a-2);
				d = strbyte(text,b+1);
				if not(c == 124 or d == 124) then
					e = strsub(text,a+1,b-1);
					text = e;
					table.insert(notLinks,1,e);
					notLinks[10] = nil;
				end
			end
		end
		
		---below from old class.insert link from this file
		local a1,b1,c1,d1,e1,ID,n1,n2 = 0;
		local link,name;
	
		off = 0;
		for i=1,5 do
			a1= string.find(text,"|H"..linkerref.."\"",0);---i suck at adding quotes.
			if a1 then
				--GHR_Message("#"..i);
				b1 = string.find(text,"|C",a-10);	
				c1 = string.find(text,"|r",a);	
				--GHR_Message(a);
				link = string.sub(text,b,c+1)
				n1 = string.find(link,"|h")
				n2 = string.find(link,"|h",n1+1);
				
				
				name = string.sub(link,n1+3,n2-2)
				
				-- find ID
				d = string.find(text,":",a);
				e = string.find(text,":",d+1);
				
				ID = string.sub(text,d+1,e-1);
				table.insert(sendLinks,1,ID);
				sendLinks[10] = nil;
				
				
				--text = gsub(text,link,"<"..name..">");
				text = strsub(text,0,b-1).."["..name.."]"..strsub(text,c+2);
			else
				break;	
			end
		end
		
		
		orig_SendChatMessage(text,...)
	end
	
	-- incomming messages
	class:SetScript("OnEvent",function(self,event,...)
		
		local mesg,sender,lang,chanString,target, flags,ukwn1, chanNum,chanName,ukwn2, counte,guid,arg13,arg14,arg15,arg16,arg17,arg18,arg19 = ...;
		
		
		-- check if the event is supported for links
		if supportedEvents[event]~= nil then
		-----------------------------
						if GHI_MiscData["block_std_emote"] == true then
		if event == "CHAT_MSG_TEXT_EMOTE" then
			if mesg == msgToBlock and sender == playerToBlock then
				return;
			elseif blockNextStdEmoteFromPlayer[sender] == true then
				msgToBlock = mesg;
				playerToBlock = sender;
				blockNextStdEmoteFromPlayer[sender] = false;
				return;				
			end
		end
		
		if event == "CHAT_MSG_EMOTE" then
			if strsub(mesg,mesg:len()-2,mesg:len()) == "   " then
				blockNextStdEmoteFromPlayer[sender] = true;
			end
		end
		
	end
	
	if event == "CHAT_MSG_SYSTEM" then
		
		--GHI_Message(gsub(ERR_CHAT_PLAYER_NOT_FOUND_S,"%%s","%%a+"));
		--local player = string.match(arg1,gsub(ERR_CHAT_PLAYER_NOT_FOUND_S,"%%s","%%a"));
		local player = gsub(string.match(mesg,"'.*'") or "","'","");
		
		if player and format(ERR_CHAT_PLAYER_NOT_FOUND_S,player) == mesg and ((GHI_MessageErrorsExpected_A[player] or GHI_MessageErrorsExpected_B[player])) then
			
			return;
		end
	end

	msgToBlock = "";
	playerToBlock = "";
	----------------------------------------------
			-- find all messages containing brackets
			
	
	        local linkText,a,b,c,d = 0;
			local hasLink = false;
			--local waitIndex = {};
			
			   for i=1,5 do
				
				a = class.SearchStringForChar(mesg,91,a+1);
				b = strfind(text,"]",a);
				if not(a == nil) and b then 
				 if not(c == 124 or d == 124) then
					c = strbyte(mesg,a-2);
					d = strbyte(mesg,b+1);
					--GHI_Message(c);
					--GHR_Message(d);
					hasLink=true;
					end
				end
			end
			

			if hasLink == false then --not a link
			
				-- parse the message to all frames in registeredFrames
				--remember to ignore _G["ChatFrame2"] via if stament, chatframe2 is the combat log!	
				for i=1, #registeredFrames do
					if i~=2  then 
				      _G["ChatFrame"..i]:AddMessage(mesg);--will need to get the proper text color for it also
					  end
				end
					
			else
				-- send a link request to the player  (use a global class to handle the comm)
			
                       
						linkText = strsub(mesg,a+1,b-1); 
						--c,d = strfind(text,linkText);
						GHI:SendPrioritizedMessage("ALERT","WHISPER",sender,false,"SuspectedLinkName",linkText)
						
	
	
	
			end
			
			
		
		
		end
		
		
		
	end);
	for _,event in pairs(supportedEvents) do 
		class:RegisterEvent(event);
	end
  
  
  -- setup
  linkerRef = "GHU"..lastLinkerID; -- unique reference to this instance of the class
  lastLinkerID = lastLinkerID + 1;
  
    
  -- unregister and save all frames registered for the chat events
  for _,event in pairs(supportedEvents) do
  	registeredFrames[event] = {GetFramesRegisteredForEvent(event)};
  	for _,frame in pairs(registeredFrames[event]) do
  		 -- if there is problems with the frames reregistering, then_ it could be an idear to hook their event functions and filter  	
			frame:UnregisterEvent(event);
  	end
  end
	  
  return class;
end







-- =============  old version =================








GHU_SendItemsID = {};
GHU_SendNotItems = {};
--GHI_RegEvent("CHAT_MSG_SAY",GHULink_Event);
--GHI_RegEvent("CHAT_MSG_YELL",GHULink_Event);
--GHI_RegEvent("CHAT_MSG_WHISPER",GHULink_Event);
--need to add others;

--[[function GHU_Links:RegEvents()---call as startup 
local eventtypes = {"SAY","YELL","WHISPER","EMOTE","RAID","PARTY","GUILD","SYSTEM"}
for i=1,#eventtypes do 
GHI_RegEvent("CHAT_MSG_"..eventtypes[1],GHULEvent);

end

GHU_OrigSetItemRef = SetItemRef;
	SetItemRef = GHU_SetItemRef;
	
	GHU_origSendChatMessage = SendChatMessage;
	SendChatMessage = GHU_SendChatMessage;
	
	-- inc chat
	GHU_origChatFrame_MessageEventHandler = ChatFrame_MessageEventHandler;
	ChatFrame_MessageEventHandler = GHU_ChatFrame_MessageEventHandler;

end

function GHU_Links:GHULEvent(...)--need to be sure i add args right
local self,event,mesg,sender,lang,chanString,target, flags,ukwn1, chanNum,chanName,ukwn2, counte,guid,arg13,arg14,arg15,arg16,arg17,arg18,arg19 = ...;
if GHI_MiscData["block_std_emote"] == true then
		if event == "CHAT_MSG_TEXT_EMOTE" then
			if mesg == msgToBlock and sender == playerToBlock then
				return;
			elseif blockNextStdEmoteFromPlayer[sender] == true then
				msgToBlock = mesg;
				playerToBlock = sender;
				blockNextStdEmoteFromPlayer[sender] = false;
				return;				
			end
		end
		
		if event == "CHAT_MSG_EMOTE" then
			if strsub(mesg,mesg:len()-2,mesg:len()) == "   " then
				blockNextStdEmoteFromPlayer[sender] = true;
			end
		end
		
	end
	
	if event == "CHAT_MSG_SYSTEM" then
		
		--GHI_Message(gsub(ERR_CHAT_PLAYER_NOT_FOUND_S,"%%s","%%a+"));
		--local player = string.match(arg1,gsub(ERR_CHAT_PLAYER_NOT_FOUND_S,"%%s","%%a"));
		local player = gsub(string.match(mesg,"'.*'") or "","'","");
		
		if player and format(ERR_CHAT_PLAYER_NOT_FOUND_S,player) == mesg and ((GHI_MessageErrorsExpected_A[player] or GHI_MessageErrorsExpected_B[player])) then
			
			return;
		end
	end
	
	msgToBlock = "";
	playerToBlock = "";
	
	if string.sub(event,1,8) == "CHAT_MSG" and not(event=="CHAT_MSG_SYSTEM") then 
	local linktext = GHU_Links.ParseLink(mesg)
	GHI:SendPrioritizedMessage("ALERT","WHISPER",sender,false,"SuspectedLinkName",linkText)
	
	end
	
end

function GHU_SendChatMessage(text, type, language, target, ...)---trying move move this into class, call the class as an event?
	--hopefully doing this right..i am trying to not convuse varibles but i need to more th en likely.
   local linkname1 = GHU_Links.ParseLink(text)
    local ltext1 = GHU_Links.RemoveLink(text)
	
	
	--GHU_Message("Handle Outgoing");

	local link,lname,ltext,linkname = GHU_Links.InsertLink(ltext1,linkname1)--may need to be just text

	
	GHU_origSendChatMessage(text, type, language, target, ...)
end



local waitIndex = {};
function GHU_Links(parent,arg1,arg2) --unsure how many args i will need in the en_d
   local class = Class("GHU_Links",parent)

 
  -- local
  -- local myLocalArg1 = arg1; -- example of local value
 ---local text,linkname,ItemID
  -- functions
  
  class.GenerateLink = function(self,ItemID,linkname)
    --local ItemID = arg1;
     if ItemID == nil then return end;
	local name,icon,quality = GHU_GetItemInfo(ItemID);
	if not(name) then return end;
	local link;
	local color = ITEM_QUALITY_COLORS[quality];
	link = "|CFF" ..string.format("%.2x",color.r*255) .. string.format("%.2x",color.g*255) .. string.format("%.2x",color.b*255) .."|H"..linkname..":"..ItemID..":0:0:0:0:0:0:0|h["..name.."]|h|r"
	
	return link,color,ItemID;
  end
 
  class.RemoveLink = function(self,text,arg2)
  	local a,b,c,d,e,f;
		a = 0;
		while a do
			--GHU_Message("A");
			a = GHI_SearchStringForChar(text,91,a+1);
			b = strfind(text,"]",a);
			if not(a == nil) and b then 
				c = strbyte(text,a-2);
				d = strbyte(text,b+1);
				if not(c == 124 or d == 124) then
					e = strsub(text,a+1,b-1);
					text = e;
					table.insert(GHU_SendNotItems,1,e);
					GHU_SendNotItems[10] = nil;
				end
			end
		end
		return text;
  end
  
  class.InsertLink = function(self,text,linkname) 
  --local text = arg1;
  
  local a,b,c,d,e,ID,n1,n2 = 0;
	local link,name;

	off = 0;
	for i=1,5 do
		a = string.find(text,"|H"..linkname.."\"",0);---i suck at adding quotes.
		if a then
			--GHR_Message("#"..i);
			b = string.find(text,"|C",a-10);	
			c = string.find(text,"|r",a);	
			--GHR_Message(a);
			link = string.sub(text,b,c+1)
			n1 = string.find(link,"|h")
			n2 = string.find(link,"|h",n1+1);
			
			
			name = string.sub(link,n1+3,n2-2)
			
			-- find ID
			d = string.find(text,":",a);
			e = string.find(text,":",d+1);
			
			ID = string.sub(text,d+1,e-1);
			table.insert(GHU_SendItemsID,1,ID);
			GHU_SendItemsID[10] = nil;
			
			
			--text = gsub(text,link,"<"..name..">");
			text = strsub(text,0,b-1).."["..name.."]"..strsub(text,c+2);
		else
			break;	
		end
	end
	return link,name,text,linkname;
  end
  
  class.ParseLink = function(self,text,arg2)---not sure what to return here
			--local text = arg1;
			local linkText,a,b,c,d = 0;
			
			--local waitIndex = {};
			a = 0;
			for i=1,5 do --GHI_Message("A -3");
				--GHI_Message("A");
				a = GHI_SearchStringForChar(text,91,a+1);
				b = strfind(text,"]",a);
				if not(a == nil) and b then --GHI_Message("a and b found in "..text);
					c = strbyte(text,a-2);
					d = strbyte(text,b+1);
					--GHI_Message(c);
					--GHR_Message(d);
					if not(c == 124 or d == 124) then
						linkText = strsub(text,a+1,b-1); 
						--c,d = strfind(text,linkText);
						
						if type(GHI_ItemData[value1]) == "table" then
							if GHI_ItemData[value1].name == linkText then
								sendToSelf = true;
								isItem = true;
								table.insert(waitIndex,value1);
								break;
							end
						end
					end
				end
			end
							
	clase.SetItemRef = function(self,link, text, button)--may need to change this
			local prefix = string.sub(link,0,6)

		if prefix ~= nil then--unsure how to handle the prefix thing besides just making sure its not nil, unsure if searching for the words GH would work
		local a = strfind(link,":",0);
		if not(a) then return end;
		local b = strfind(link,":",a+1);
		if not(b) then return end;
			
		local ID = strsub(link,a+1,b-1);
		if IsShiftKeyDown() == 1 then
			local GHU_link,color,itemID = GHU_Links.GenerateLink(ID,prefix);--prefix being the linkname
			if ( not(ChatEdit_InsertLink(GHU_link)) and not(GHU_FCCC_InsertLink(GHU_link)) ) then
			end
		else
			if ItemRefTooltip:IsShown() and GHU_LastLinkID == ID then
				ItemRefTooltip:Hide();
			else
				GHU_Links.ItemRefTooltip(ID);
			end
		end
		
		GHU_LastLinkID = ID;
	else
		GHU_OrigSetItemRef(link, text, button);
		GHU_LastLinkID = 0;
	end
    end

  clase.ItemRefTooltip = function(self,ItemID) 
	ShowUIPanel(ItemRefTooltip);
	if ( not ItemRefTooltip:IsShown() ) then
		ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE");
	end
	GHI_SetTooltipInfo(ItemRefTooltip,ItemID);
	ItemRefTooltip:Show();	
  end
  end
  
  -- Hooks
	
	  
  
  -- setup
  --  class:Start() -- example of something run as setup
  ---class:RegEvents()
  return class;
end
]]


--	Catch item links in outgoing text



