-- Credits: Tekkub, AnduinLothar
-- stitching together bits and pieces from tekPlayerMenu, ReURL

local addonName, addonTable = ...
local L = addonTable.L
local R_S = REALM_SEPARATORS:sub(1,1)

local Armories = {
	[1] = {label = L.BLIZZARD, base = ".battle.net/wow/"},
	[2] = {label = L.ARMORYLITE, base = "http://armorylite.com/"},
	[3] = {label = L.WOWHEROES, base = "http://wow-heroes.com/character/"}, 
	[4] = {label = L.WOWHEAD, base = "http://www.wowhead.com/profile="},
	[5] = {label = L.GUILDOX, base = "http://www.guildox.com/go/g.asp?a=8&p="},
}

local supportedRegion = {
	["us"] = true,
	["eu"] = true,
	["kr"] = true,
	["tw"] = true,
	["cn"] = true,
}

ArmoryQL_Config = {};

UnitPopupButtons["AQL"]={text = L.ARMORYQUICKLINK, dist = 0};
table.insert(UnitPopupMenus["FRIEND"], #(UnitPopupMenus["FRIEND"])-1, "AQL");
table.insert(UnitPopupMenus["PARTY"], #(UnitPopupMenus["PARTY"])-1, "AQL");
table.insert(UnitPopupMenus["RAID_PLAYER"], #(UnitPopupMenus["RAID_PLAYER"])-1, "AQL");

local function urlEscape(url)
	return string.gsub(url, "([^A-Za-z0-9_:/?&=.-])", 
		function(ch)
			return string.format("%%%02x", string.byte(ch))
		end)
end

local function constructUrl(name,server)
	if not name or name == "" then return end
	
	if not server or server == "" then server = GetRealmName() end

	local zone, tempurl, url;
	
	zone = GetCVar("realmList"); 
	if zone then
		zone = string.split(".", zone);
		zone = string.lower(zone)
		if not zone or zone == "" then
			DEFAULT_CHAT_FRAME:AddMessage(L.AQLCOLORLABEL..L.REALMERROR);
			return;
		end
	end
	
	if not server or server == "" then
		DEFAULT_CHAT_FRAME:AddMessage(L.AQLCOLORLABEL..L.SERVERERROR);
		return;
	end
		
	if not supportedRegion[zone] then
		DEFAULT_CHAT_FRAME:AddMessage(L.AQLCOLORLABEL.."["..string.upper(zone).."]"..L.NOTSUPPORTEDLIST);
		zone = nil;
		return;
	end
	
	if not ArmoryQL_Config.ArmoryID or not Armories[ArmoryQL_Config.ArmoryID] then
		ArmoryQL_Config.ArmoryID = 1;
	end
	
	if ArmoryQL_Config.ArmoryID == 1 then -- Blizzard
		server = server:gsub("'","");
		server = server:gsub(" ","-");
		url = "http://"..zone..Armories[ArmoryQL_Config.ArmoryID].base..L.LANGUAGE.."/character/"..server.."/"..name.."/advanced";
	elseif ArmoryQL_Config.ArmoryID ==2 then -- ArmoryLite
		url = Armories[ArmoryQL_Config.ArmoryID].base..zone.."/"..server.."/"..name;
	elseif ArmoryQL_Config.ArmoryID ==3 then -- WoW heroes
		url = Armories[ArmoryQL_Config.ArmoryID].base..zone.."/"..server.."/"..name.."/";
	elseif ArmoryQL_Config.ArmoryID ==4 then -- wowhead
		if zone == "eu" or zone == "us" then		
			server = server:gsub("'","");
			server = server:gsub(" ","-");
			tempurl = Armories[ArmoryQL_Config.ArmoryID].base..zone.."."..server..".".. name;
		else
			tempurl = nil;
		end
		if tempurl then
			url = tempurl;
		end
	elseif ArmoryQL_Config.ArmoryID ==5 then -- GuildOx
		if zone == "cn" then		
			tempurl = nil;
		else
			tempurl = Armories[ArmoryQL_Config.ArmoryID].base..name.."&r="..server.."-"..zone;
		end
		if tempurl then
			url = tempurl;
		end	
	end
	
	if url then
		url = urlEscape(url);
	end 
	
	return url;
end

local function ShowUrl(name,server)
	if not name then return end
	local n,s = strmatch(name,format("(.+)%s(.+)",R_S))
	if n and s then name,server = n,s end
	local url = constructUrl(name,server);
	if url then
		local edit_box = ChatEdit_ChooseBoxForSend()
		ChatEdit_ActivateChat(edit_box)
		if url then
			edit_box:Insert(url);
			edit_box:HighlightText();
		end
	end
end

hooksecurefunc("UnitPopup_HideButtons", function(self)
	local dropdownMenu = UIDROPDOWNMENU_INIT_MENU
	for k,v in pairs(UnitPopupMenus[dropdownMenu.which]) do
		if v == "AQL" then 
			UnitPopupShown[k] = (dropdownMenu.name == UnitName("player") and 0) or 1 
		end
	end
end)

hooksecurefunc("UnitPopup_OnClick", function(self)
	local dropdownFrame = UIDROPDOWNMENU_INIT_MENU
	local button = self.value
	if button == "AQL" then
		ShowUrl(dropdownFrame.name, dropdownFrame.server);
	end
end)


local pName;
local AQLMenuTable = {{text = L.ARMORYQUICKLINK, checked = nil, notCheckable = 1, func = function() ShowUrl(pName,pServer) end,},}
local AQLDropDownMenu = CreateFrame("Frame", "AQLDropDownMenu", nil, "UIDropDownMenuTemplate")

do
	for i=1, NUM_LFR_LIST_BUTTONS do
		local browseButton = _G["LFRBrowseFrameListButton"..i]
			browseButton:HookScript("OnMouseUp", function(self, button) 
				if button == "RightButton" then 
					pName = self.name and self.name:GetText()
					EasyMenu(AQLMenuTable, AQLDropDownMenu, self, 50, 0, "MENU", 3)
				end
			end);
	end
end

local function ArmoryQuickLink_Help()
	DEFAULT_CHAT_FRAME:AddMessage(L.AQLCOLORLABEL.."/aql x (selects profiler)");
	for i=1,#(Armories) do
		DEFAULT_CHAT_FRAME:AddMessage(Armories[i].label);
	end
end

local function ArmoryQuickLink_Slash(cmd)
	if not cmd or cmd == "" then
		ArmoryQuickLink_Help();
		return;
	end
	local id = tonumber(cmd);
	if not id then
		ArmoryQuickLink_Help();
		return;
	end
	if not Armories[id] then
		ArmoryQuickLink_Help();
		return;
	end
	ArmoryQL_Config.ArmoryID = id;
	DEFAULT_CHAT_FRAME:AddMessage(L.AQLCOLORLABEL.."- "..Armories[id].label);
end

SLASH_ARMORYQUICKLINK1 = "/armoryquicklink";
SLASH_ARMORYQUICKLINK2 = "/aql";
SlashCmdList["ARMORYQUICKLINK"] = ArmoryQuickLink_Slash;

--[[todo:
NFC, NFKC unicode normalization implemented in Lua needed for the part of the URI before name
example: Pozzo dell'Eternita realm becomes
http://eu.battle.net/wow/it/character/pozzo-delleternita/Pentolaccia/simple]]