-- Inspired from URL Copy v1.2.11000 by Leuchtturm on Azshara EU

Prat_UrlCopy = Prat:NewModule('urlcopy')

function Prat_UrlCopy:OnInitialize()
    self.db = Prat:AcquireDBNamespace('UrlCopy')

    Prat:RegisterDefaults('UrlCopy', 'profile', {
        on = true,
	  	bracket = true,
	  	popup = true,
        color = {
            r = 1,
            g = 1,
            b = 1,
		on = true
        },
    })

    Prat.Options.args.urlcopy = {
        name = 'UrlCopy',
        desc = 'URL Copy',
        type = 'group',
        args = {
		bracket = {
			type = "toggle",
			name = "Bracket",
			desc = "Show Bracket", 
			get = function() return self.db.profile.bracket end,
			set = function(v) self.db.profile.bracket = v end,
		},
		popup = {
			type = "toggle",
			name = "Popup",
			desc = "Use popup window to show URL", 
			get = function() return self.db.profile.popup end,
			set = function(v) self.db.profile.popup = v end,
		},
            color = {
                name = 'Color',
                type = 'group',
                desc = 'Settings for the color of the URL.',
                args = {
                    color = {
                        name = 'Color',
                        type = 'color',
                        desc = "Change the color of the URL.",
                        get = function() return self.db.profile.color.r, self.db.profile.color.g, self.db.profile.color.b end,
                        set = function(r, g, b, a) self.db.profile.color.r, self.db.profile.color.g, self.db.profile.color.b = r, g, b end,
                    },
                    toggle = {
                        name = 'Toggle',
                        desc = 'Toggle the URL color on and off.',
                        type = 'toggle',
                        get = function() return self.db.profile.color.on end,
                        set = function(v) self.db.profile.color.on = v end
                    }
                }
            },
       	toggle = {
                name = 'Toggle',
                desc = 'Toggle the module on and off',
                type = 'toggle',
                get = function() return self.db.profile.on end,
                set = function(v)
                    if v then
                        self:OnEnable()
                    else
                        self:OnDisable()
                    end
                    self.db.profile.on = v
                end
            },
        }
    }
end


function Prat_UrlCopy:OnEnable()
    for i=1,NUM_CHAT_WINDOWS do
        self:Hook(getglobal('ChatFrame'..i), 'AddMessage')
    end

    self:Hook('SetItemRef')
end

function Prat_UrlCopy:OnDisable()
    for i=1,NUM_CHAT_WINDOWS do
        self:Unhook(getglobal('ChatFrame'..i), 'AddMessage')
    end

    self:Unhook('SetItemRef')
end


---- Hook


function Prat_UrlCopy:AddMessage(frame, text, ...)
	text = Prat_UrlCopy:ProcessText (text)

	self.hooks[frame].AddMessage.orig(frame, text, unpack(arg))
end


function Prat_UrlCopy:SetItemRef(link, text, button)
	if ( strsub(link, 1, 3) == "url" ) then
		Prat_UrlCopy:ShowUrl(link)
	else
		self.hooks.SetItemRef.orig(link, text, button);
	end
end

-- Utility Function 

function Prat_UrlCopy:Link (link)


-- reference line for color :
-- link = " |cff" .. URLCopy.Color .. "|Hurl:" .. link .. "|h[" .. link .. "]|h|r "

	returnedLink = " "

      if self.db.profile.color.on then
            local color = string.format("%02x%02x%02x", self.db.profile.color.r*255, self.db.profile.color.g*255, self.db.profile.color.b*255)
            returnedLink = " |cff" .. color
      end

	returnedLink = returnedLink .. "|Hurl:" .. link .. "|h"

	if ( self.db.profile.bracket ) then
		returnedLink = returnedLink .. "[" .. link .. "]"
	else
		returnedLink = returnedLink .. link
	end

	returnedLink = returnedLink .. "|h|r "

	return returnedLink
end

function Prat_UrlCopy:ProcessText(text)
	text = Prat_UrlCopy:Decompose(text)

	return text
end

function Prat_UrlCopy:Decompose (chatstring)
	if chatstring ~= nil then
		-- www.X.Y url
		chatstring = string.gsub (chatstring, " www%.([_A-Za-z0-9-]+)%.(%S+)%s?", Prat_UrlCopy:Link ("www.%1.%2"))

		-- X://Y url
		chatstring = string.gsub (chatstring, " (%a+)://(%S+)%s?", Prat_UrlCopy:Link ("%1://%2"))

		-- X@X.Y url (---> email)
		chatstring = string.gsub (chatstring, " ([_A-Za-z0-9-%.]+)@([_A-Za-z0-9-]+)%.([_A-Za-z0-9-%.]+)%s?", Prat_UrlCopy:Link ("%1@%2.%3"))

		-- XXX.YYY.ZZZ.WWW:VVVV url (IP of ts server for example)
		chatstring = string.gsub (chatstring, " (%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?):(%d%d?%d?%d?%d?)%s?", Prat_UrlCopy:Link ("%1.%2.%3.%4:%5"))

		-- XXX.YYY.ZZZ.WWW url (---> IP)
		chatstring = string.gsub (chatstring, " (%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%s?", Prat_UrlCopy:Link ("%1.%2.%3.%4"))

		-- X.Y.Z url
		-- original, not good because takes v1.1.0 like an URL for example		
		chatstring = string.gsub (chatstring, " ([_A-Za-z0-9-]+)%.([_A-Za-z0-9-]+)%.(%S+)%s?", Prat_UrlCopy:Link ("%1.%2.%3"))
		-- test :
		-- chatstring = string.gsub (chatstring, " ([_A-Za-z0-9-]+)%.(%S+).([_A-Za-z-]+)%%s?", Prat_UrlCopy:Link ("%1.%2.%3"))

		-- X.Y.Z:WWWW url  (ts server for example)
		chatstring = string.gsub (chatstring, " ([_A-Za-z0-9-]+)%.([_A-Za-z0-9-]+)%.(%S+)%:([_0-9-]+)%s?", Prat_UrlCopy:Link ("%1.%2.%3:%4"))
		
	end
	return chatstring
end

function Prat_UrlCopy:ToggleFrame(link)
	StaticPopupDialogs["SHOW_URL"] = {
		text = "URL : %s",
		button2 = TEXT(ACCEPT), 
		hasEditBox = 1,
		hasWideEditBox = 1,
		showAlert = 1, -- HACK : it's the only way I found to make de StaticPopup have sufficient width to show WideEditBox :(

		OnShow = function() 
			local editBox = getglobal(this:GetName().."WideEditBox");
			editBox:SetText(format(link));
			editBox:SetFocus(); 
			editBox:HighlightText(0); 
			
			local button = getglobal(this:GetName().."Button2");
			button:ClearAllPoints();
			button:SetWidth(200);
			button:SetPoint("CENTER", editBox, "CENTER", 0, -30);

			getglobal(this:GetName().."AlertIcon"):Hide();  -- HACK : we hide the false AlertIcon
		end,		

		OnHide = function() end,
		OnAccept = function() end,
		OnCancel = function() end,
		EditBoxOnEscapePressed = function() this:GetParent():Hide(); end,
		timeout = 0,
		whileDead = 1,
		hideOnEscape = 1
	};

	StaticPopup_Show ("SHOW_URL", link);
end

function Prat_UrlCopy:EditBoxUrl(link)
	if (not ChatFrameEditBox:IsShown()) then
		ChatFrame_OpenChat(link, DEFAULT_CHAT_FRAME);
	else
		ChatFrameEditBox:Insert(link);
	end	
end

function Prat_UrlCopy:ShowUrl(link)
	link = strsub(link, 5)
	if ( self.db.profile.popup ) then
		Prat_UrlCopy:ToggleFrame(link)
	else
		Prat_UrlCopy:EditBoxUrl(link)
	end
end
