
-------------------------------------------------------------------------------
--
--  Mod Name : BlinkMod v2.0
--  Author   : Blink
--  Date     : 2005/07/16
--  LastUpdate : 2009/12/18
--
-------------------------------------------------------------------------------

local tinsert = table.insert
local tremove = table.remove
local tsort = table.sort
local wipe = table.wipe

-- Variables ------------------------------------------------------------------
local debug = false

BlinkMod_MenuFuncs = {}

-- First Level Menus
BlinkMod_Menus = {}
BlinkMod_Menus["SELF"] = {}
BlinkMod_Menus["PET"] = {}
BlinkMod_Menus["PARTY"] = {}
BlinkMod_Menus["PLAYER"] = {}
BlinkMod_Menus["RAID_PLAYER"] = {}
BlinkMod_Menus["RAID"] = {}
BlinkMod_Menus["FRIEND"] = {}
BlinkMod_Menus["FRIEND_OFFLINE"] = {}
BlinkMod_Menus["BN_FRIEND"] = {}
BlinkMod_Menus["BN_FRIEND_OFFLINE"] = {}
BlinkMod_Menus["TEAM"] = {}
BlinkMod_Menus["RAID_TARGET_ICON"] = {}
BlinkMod_Menus["SELECT_ROLE"] = {}
BlinkMod_Menus["CHAT_ROSTER"] = {}
BlinkMod_Menus["VEHICLE"] = {}
BlinkMod_Menus["TARGET"] = {}
BlinkMod_Menus["ARENAENEMY"] = {}
BlinkMod_Menus["FOCUS"] = {}
BlinkMod_Menus["BOSS"] = {}

BlinkMod_Menus["ENEMY"] = {}
BlinkMod_Menus["NPC"] = {}

UnitPopupMenus["ENEMY"] = { "INSPECT", "RAID_TARGET_1", "RAID_TARGET_2", "RAID_TARGET_3", "RAID_TARGET_4", "RAID_TARGET_5", "RAID_TARGET_6", "RAID_TARGET_7", "RAID_TARGET_8", "RAID_TARGET_NONE" }
UnitPopupMenus["NPC"] = { "RAID_TARGET_1", "RAID_TARGET_2", "RAID_TARGET_3", "RAID_TARGET_4", "RAID_TARGET_5", "RAID_TARGET_6", "RAID_TARGET_7", "RAID_TARGET_8", "RAID_TARGET_NONE" }

-- Sencond Level Menus
BlinkMod_SecondMenus = {}

BlinkMod_Focus = {}

-- Debug Print ----------------------------------------------------------------
function BlinkMod_DebugPrint(msg)
	if ( debug == true ) then
		if(ChatFrame1) then
			ChatFrame1:AddMessage("BM : "..msg, 1.0, 0.2, 0.2)
		end
	end
end

-- OnLoad ---------------------------------------------------------------------
function BlinkMod_OnLoad()

	--[[ OMFG!!!!!!!!!!!!
	local unitIDs = {"player", "target", "pet", "party1", "party2", "party3", "party4", "arena1", "arena2", "arena3", "arena4", "arena5"}
	local button
	for i=1, #unitIDs do
		button = CreateFrame("Button", "BM_FocusButton"..unitIDs[i], UIParent, "SecureActionButtonTemplate")
		button:SetAttribute("type", "macro")
		button:SetAttribute("macrotext", "/focus "..unitIDs[i])
		button:RegisterForClicks("LeftButtonDown")
		button:Hide()
		BlinkMod_Focus[ unitIDs[i] ] = button
	end
	BlinkMod_Focus["focus"] = CreateFrame("Button", "BM_ClearFocusButton", UIParent, "SecureActionButtonTemplate")
	BlinkMod_Focus["focus"]:SetAttribute("type", "macro")
	BlinkMod_Focus["focus"]:SetAttribute("macrotext", "/CLEARFOCUS")
	BlinkMod_Focus["focus"]:RegisterForClicks("LeftButtonDown")
	BlinkMod_Focus["focus"]:Hide()
	]]

	for p, v in pairs(UnitPopupMenus) do
		for i = 1, #v do
			if v[i] == "SET_FOCUS" or v[i] == "CLEAR_FOCUS" or v[i] == "TARGET" or v[i] == "CANCEL" then
				tremove(UnitPopupMenus[p], i)
			end
		end
	end

	hooksecurefunc("UnitPopup_ShowMenu", function(dropdownMenu, which, unit, name, userData) BlinkMod_UnitPopup_ShowMenu(dropdownMenu, which, unit, name, userData) end)
end

function BlinkMod_UnitPopup_ShowMenu(dropdownMenu, which, unit, name, userData)
	if unit == "target" then
		if ( not UnitIsPlayer("target") ) then
			which = "NPC"
		elseif ( UnitPlayerControlled("target") and UnitFactionGroup("target")~=UnitFactionGroup("player") ) then
			-- enemy
			which = "ENEMY"
		end
	end

	local server = nil
	-- Init variables
	dropdownMenu.which = which
	dropdownMenu.unit = unit
	if ( unit ) then
		name, server = UnitName(unit)
	elseif ( name ) then
		local n, s = strmatch(name, "^([^-]+)-(.*)")
		if ( n ) then
			name = n
			server = s
		end
	end
	dropdownMenu.name = name
	dropdownMenu.userData = userData
	dropdownMenu.server = server

	local count = 0

	local info
	local color
	local icon
	if UIDROPDOWNMENU_MENU_LEVEL == 2 then
		if ( BlinkMod_SecondMenus[UIDROPDOWNMENU_MENU_VALUE] ) then
			dropdownMenu.which = UIDROPDOWNMENU_MENU_VALUE;
			-- Set which menu is being opened
			OPEN_DROPDOWNMENUS[UIDROPDOWNMENU_MENU_LEVEL] = {which = dropdownMenu.which, unit = dropdownMenu.unit};
			info = UIDropDownMenu_CreateInfo()
			for index, value in ipairs(BlinkMod_SecondMenus[UIDROPDOWNMENU_MENU_VALUE]) do
				--value = value
				if ( not value.ShowHideFunction or (value.ShowHideFunction and value.ShowHideFunction(dropdownMenu) == true) ) then
					info.text = value.text;
					if ( value.GetNameFunction ) then
						info.text = value.GetNameFunction(value.text, dropdownMenu)
					end
					if ( value.CheckFunction and value.CheckFunction(dropdownMenu) == true ) then
						info.checked = 1
					else
						info.checked = nil
					end
					info.value = value.key
					info.owner = value.parentkey
					if value.ClickFunction and type(value.ClickFunction)=='function' then
						--value.func = BlinkMod_Second_OnClick
						info.func = function (self)
							value.ClickFunction(UIDROPDOWNMENU_INIT_MENU)
						end
					end
					-- Icons
					info.icon = value.icon;
					info.tCoordLeft = value.tCoordLeft;
					info.tCoordRight = value.tCoordRight;
					info.tCoordTop = value.tCoordTop;
					info.tCoordBottom = value.tCoordBottom;

					info.tooltipTitle = value.tooltipTitle
					info.tooltipText = value.tooltipText
					UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL)
					count = count + 1
				end
			end
		end
		if #BlinkMod_MenuFuncs>0 then
			for i=1, #BlinkMod_MenuFuncs do
				count = count + (BlinkMod_MenuFuncs[i](UIDROPDOWNMENU_MENU_VALUE) or 0)
			end
		end
		return
	end

--	-- FOCUS
--	-- OMFG!!!!!!!!!!!!!!!!!!
--	if unit and BlinkMod_Focus[unit] then
--		info = UIDropDownMenu_CreateInfo()
--		info.text = unit=="focus" and CLEAR_FOCUS or SET_FOCUS
--		info.owner = which
--		info.func = function ()
--			BlinkMod_Focus[unit]:Click()
--			--SecureActionButton_OnClick(BlinkMod_Focus[unit])
--		end
--		UIDropDownMenu_AddButton(info)
--		count = count + 1
--	end

	-- 추가적인 팝업메뉴들
	if ( BlinkMod_Menus[which] ) then
		info = UIDropDownMenu_CreateInfo()
		for index, value in ipairs(BlinkMod_Menus[which]) do
			if ( not value.ShowHideFunction or (value.ShowHideFunction and value.ShowHideFunction(dropdownMenu) == true) ) then
				if ( value.GetNameFunction ) then
					info.text = value.GetNameFunction(value.text, dropdownMenu)
				end
				if ( value.CheckFunction and value.CheckFunction(dropdownMenu) == true ) then
					info.checked = 1
				else
					info.checked = nil
				end
				if value.ClickFunction and type(value.ClickFunction)=='function' then
					--info.func = BlinkMod_OnClick
					info.func = function (self)
						value.ClickFunction(UIDROPDOWNMENU_INIT_MENU)
					end
				end
				info.value = value.key
				info.owner = value.parentkey

				-- Icons
				info.icon = value.icon
				info.tCoordLeft = value.tCoordLeft
				info.tCoordRight = value.tCoordRight
				info.tCoordTop = value.tCoordTop
				info.tCoordBottom = value.tCoordBottom

				info.tooltipTitle = value.tooltipTitle
				info.tooltipText = value.tooltipText

				UIDropDownMenu_AddButton(info, 1)
				count = count + 1
			end
		end
		if #BlinkMod_MenuFuncs>0 then
			for i=1, #BlinkMod_MenuFuncs do
				count = count + (BlinkMod_MenuFuncs[i](which) or 0)
			end
		end
	end

	if count == 0 then
		return
	end

	-- 취소버튼
	local info = UIDropDownMenu_CreateInfo()
	info.text = CANCEL
	info.value = "CANCEL"
	info.owner = which
	info.func = function () end
	info.notCheckable = 1
	info.tooltipTitle = CANCEL
	info.tooltipText = nil
	UIDropDownMenu_AddButton(info)
end

-- BlinkMod_RemoveMenu --------------------------------------------------------
function BlinkMod_RemoveMenu(parent,key,level)
	local removeKey = -1
	local t = nil

	if ( not parent ) then
		return
	end
	if ( not key ) then
		return
	end
	if ( not level ) then
		level = 1
	end

	if ( level == 1 ) then
		for i=1,#BlinkMod_Menus[parent],1 do
			if ( BlinkMod_Menus[parent][i].key == key ) then
				removeKey = i
				break
			end
		end
		if ( removeKey > -1 ) then
			table.remove(BlinkMod_Menus[parent],i)
		end
	elseif ( level == 2 ) then
		for i=1,#BlinkMod_SecondMenus[parent],1 do
			if ( BlinkMod_SecondMenus[parent][i].key == key ) then
				removeKey = i
				break
			end
		end
		if ( removeKey > -1 ) then
			table.remove(BlinkMod_SecondMenus[parent],i)
		end
	end
end



function BlinkMod_RegisterFunc(func, ...)
	if type(func)~='function' then
		return
	end
	tinsert(BlinkMod_MenuFuncs, func)

	local count = select('#', ...)
	local key
	for i=1, count do
		key = select(i, ...)
		if not UnitPopupMenus[key] then
			UnitPopupMenus[key] = {}
		end
	end
end

--[[
List of button attributes
======================================================
info.key = [STRING] -- 버튼의 키값(필수)
info.parentkey = [STRING] -- 상위버튼의 키값(필수)

info.text = [STRING]  --  버튼이름(필수)
info.checked = [nil, 1]  --  버튼이 체크되어있는가?
info.isTitle = [nil, 1]  --  타이틀버튼인가? (타이틀버튼이라면 클릭이 안되며, 글자색은 노란색으로 보입니다.)
info.disabled = [nil, 1]  --  클릭할수 없는 버튼인가?
info.hasArrow = [nil, 1]  --  화살표가 있는 버튼인가? (하위메뉴를 가질수 있는가를 설정하는 변수)
info.hasColorSwatch = [nil, 1]  --  컬러색상을 선택하는 버튼인가?
info.r = [1 - 255]  --  선택된컬러값 Red
info.g = [1 - 255]  --  선택된컬러값 Green
info.b = [1 - 255]  --  선택된컬러값 Blue
info.textR = [1 - 255]  --  버튼글자색 Red
info.textG = [1 - 255]  --  버튼글자색 Green
info.textB = [1 - 255]  --  버튼글자색 Blue
info.swatchFunc = [function()]  --  컬러선택창에서 컬러값이 바뀔때마다 호출되는 함수
info.hasOpacity = [nil, 1]  --  컬러선택창에 투명도선택 슬라이드바를 보여줄것인지 선택하는 변수
info.opacity = [0.0 - 1.0]  --  선택된 투명도를 나타내는 값 1.0은 불투명, 0은 완전투명
info.opacityFunc = [function()]  --  투명도슬라이드값을 바꿀대마다 호출되는 함수
info.cancelFunc = [function(previousValues)] -- 컬러선택창에서 취소버튼을 눌렀을때 호출되는 함수 (이 함수는 이전값을 매개변수로 갖습니다. - it takes the previous values as its argument)
info.notClickable = [nil, 1]  --  클릭할수 없는 버튼으로 만드는 변수(글자색은 흰색)
info.notCheckable = [nil, 1]  --  Shrink the size of the buttons and don't display a check box
info.owner = [Frame]  --  현재 드롭다운리스트의 부모 드롭다운프레임(Dropdown frame that "owns" the current dropdownlist)
info.keepShownOnClick = [nil, 1]  --  버튼을 클릭해도 메뉴가 사라지지 않도록하는 변수
info.tooltipTitle = [nil, STRING] -- 버튼에 마우스를 올렸을때 나타나는 툴팁의 타이틀
info.tooltipText = [nil, STRING] -- 버튼에 마우스를 올렸을때 나타나는 툴팁내용
info.justifyH = [nil, "CENTER"] -- 버튼 정렬

info.ClickFunction = [function()] -- 버튼을 클릭하면 호출되는 함수
info.GetNameFunction = [function()] -- 버튼의 이름을 설정하는 함수
info.CheckFunction = [function()] -- 현재 버튼이 체크되어있는지 확인하는 함수
info.ShowHideFunction = [function()] -- 현재 버튼이 보여지는지 확인하는 함수
]]--
function BlinkMod_RegisterMenu( info, level )
	if not info then
		BlinkMod_DebugPrint("\"info\" is not exists.")
		return
	end

	if ( not level ) then
		level = 1
	end
	if ( type(info) ~= "table" ) then
		BlinkMod_DebugPrint("\"info\" is not table.")
		return
	end

	if ( not info.key ) then
		BlinkMod_DebugPrint("\"key\" arg is nil.")
		return
	end

	if ( not info.parentkey ) then
		BlinkMod_DebugPrint("\"parentkey\" arg is nil.")
		return
	end

	if not UnitPopupMenus[info.key] then
		UnitPopupMenus[info.key] = {}
	end

	if ( level == 1 ) then
		local dup = false
		local dupkey = "dupkey"
		if ( BlinkMod_Menus[info.parentkey] ) then
			for idx,menu in pairs(BlinkMod_Menus[info.parentkey]) do
				if ( menu and menu.key == info.key ) then
					dup = true
					dupkey = info.key
					break
				end
			end
		end
		if ( dup == true ) then
			BlinkMod_DebugPrint("1. Duplicated Key : "..dupkey)
			return
		end
		tinsert(BlinkMod_Menus[info.parentkey], info)
	elseif ( level == 2 ) then
		local dup = false
		local dupkey = "dupkey"
		if ( BlinkMod_SecondMenus[info.parentkey] ) then
			for idx,menu in pairs(BlinkMod_SecondMenus[info.parentkey]) do
				if ( menu and menu.key == info.key ) then
					dup = true
					dupkey = info.key
					break
				end
			end
		end
		if ( dup == true ) then
			BlinkMod_DebugPrint("2. Duplicated Key : "..dupkey)
			return
		end
		if ( not BlinkMod_SecondMenus[info.parentkey] ) then
			BlinkMod_SecondMenus[info.parentkey] = {}
		end
		table.insert(BlinkMod_SecondMenus[info.parentkey],info)
	else
		BlinkMod_DebugPrint("Wrong level value!")
	end
end

function BlinkMod_OnClick(self)
	local key = self.value
	local dropdownFrame = UIDROPDOWNMENU_INIT_MENU
	local clickfunc
	for index, value in pairs(BlinkMod_Menus[self.owner]) do
		if ( value.key == key ) then
			clickfunc = value.ClickFunction
			break
		end
	end

	if ( clickfunc and type(clickfunc)=='function' ) then
		clickfunc(dropdownFrame)
	end
	PlaySound("UChatScrollButton")
end

function BlinkMod_Second_OnClick(self)
	local key = self.value
	local dropdownFrame = UIDROPDOWNMENU_INIT_MENU
	local clickfunc
	for index, value in pairs(BlinkMod_SecondMenus[self.owner]) do
		if ( value.key == key ) then
			clickfunc = value.ClickFunction
			break
		end
	end

	if ( clickfunc and type(clickfunc)=='function' ) then
		clickfunc(dropdownFrame)
	end
	PlaySound("UChatScrollButton")
end


-- start
BlinkMod_OnLoad()
