BINDING_HEADER_TOOLSCOMMONBIND	= "연장의 단축키 모음"
BINDING_NAME_ToolsBoxTOGGLE	= "연장상자 미니맵 토글"

ToolsVersion = "07.06.24_R2"

local pText = {
	"BOTTOMLEFT","BOTTOM","BOTTOMRIGHT","LEFT", "CENTER","RIGHT","TOPLEFT","TOP","TOPRIGHT"}
local bTexture = {
	"Interface/Tooltips/UI-Tooltip-Border",
	"Interface\\AddOns\\Tools\\Border\\Square_Border1",
	"Interface/DialogFrame/UI-DialogBox-Border",
	""}

local MinimapOutline = 80
local tmpTimerData = {}
local Dropdown
local db,minimapdb

ToolsDropdown = {Common = {{},{},{}}}

local function strchk(v)
	return (type(v)=="string") and getglobal(v) or v
end

local function chkdb()
--[[	if (
		(GetMinimapShape and type(GetMinimapShape) == "function" and GetMinimapShape() == "SQUARE") or -- Squeenix
		(IsAddOnLoaded("WindMinimap") and -- WindMinimap
		((WindMinimapConfigAll and WindMinimapConfigAll["Body"][8] and WindMinimapConfigAll["Body"][8] == 2) or
		(WindMinimapBodyConfig and WindMinimapBodyConfig[8] and WindMinimapBodyConfig[8] == 2))) or
		(IsAddOnLoaded("simpleMinimap") and simpleMinimap_Skins and simpleMinimap_Skins:GetShape() == "square") -- simpleMinimap
		) then
		-- SquareMinimap Process Start
		ToolsCommonDB = ToolsCommonDB or {Minimap = {
					IconPos = { ToolsMinimap = 318 },
					Square =  true, 
					Lock = {},
					Hide = {}}}
	else  --]]
		ToolsCommonDB = ToolsCommonDB or {Minimap = {
					IconPos = { ToolsMinimap = 318 },
					Square = false, 
					Lock = {},
					Hide = {}}}
	--end
	db = ToolsCommonDB
	minimapdb = db.Minimap
end


ToolsStrCheck = strchk

-- 공통으로 사용할 프레임 제작
local commonframe = CreateFrame("Frame", "ToolsCommonFrame")
-------------------------------------------------------------------------------------■[ 프레임 ]
function Tools_SetPoint(frame, p1, base, p2, x, y)
	frame = strchk(frame)
	frame:ClearAllPoints()
	frame:SetPoint(pText[p1] or p1, (base == 0) and UIParent or base, pText[p2] or p2, x, y)
end
function Tools_SetSize(frame, width, height)
	frame = strchk(frame)
	frame:SetWidth(width)
	frame:SetHeight(height)
end
function Tools_GetSize(frame)
	return strchk(frame):GetWidth(), strchk(frame):GetHeight()
end
function Tools_SetBackdrop(frame, edgeSize, borderInset, strata, edgefile, bgfile)
	frame = strchk(frame)
	borderInset = borderInset or 4
	frame:SetFrameStrata(strata or "BACKGROUND")
	frame:SetBackdrop({
		bgFile = bgfile or "Interface/Tooltips/UI-Tooltip-Background",
		edgeFile = bTexture[edgefile] or bTexture[1],
		tile = true, tileSize = 5, edgeSize = edgeSize or 16,
		insets={left = borderInset,
			right = borderInset,
			top = borderInset,
			bottom = borderInset}})
	frame:SetBackdropBorderColor(1,1,1,1)
	frame:SetBackdropColor(0,0,0,0.4)
end
function Tools_SetBorderColor(frame, r, g, b, a, t)
	frame = strchk(frame)
	frame[(t) and "SetBackdropBorderColor" or "SetBackdropColor"](frame, r,g,b,a)
end
Tools_SetShow = function (frame, v)
	frame = strchk(frame)
	frame[(v == 1 or v == true) and "Show" or "Hide"](frame)
end
function FrameManager(v)
	if (v.Point) then
		Tools_SetPoint(v.Frame, unpack(v.Point))
	end
	if (v.Show) then
		Tools_SetShow(v.Frame, v.Show)
	end
	if (v.Size) then
		Tools_SetSize(v.Frame, unpack(v.Size))
	end
	if (v.Scale) then
		strchk(v.Frame):SetScale(v.Scale)
	end
	if (v.Border) then
		if (type(v.Border) == "table") then
			Tools_SetBackdrop(v.Frame, unpack(v.Border))
		elseif (v.Border == true) then
			Tools_SetBackdrop(v.Frame)
		end
	end
	if (v.Color) then
		if (v.Color.border) then
			strchk(v.Frame):SetBackdropBorderColor(unpack(v.Color.border))
		end
		if (v.Color.backdrop) then
			strchk(v.Frame):SetBackdropColor(unpack(v.Color.backdrop))
		end
	end
end
-------------------------------------------------------------------------------------■[ 미니맵 ]
local function CheckMinimapAddons()
	if IsAddOnLoaded("WindMinimap") then
		if WindMinimapConfigAll["Body"][8] == 2 then
			minimapdb.Square = true
			return
		end
	elseif IsAddOnLoaded("Squeenix") then
		minimapdb.Square = true
		return
	elseif IsAddOnLoaded("ToolsSquareMinimap") then
		minimapdb.Square = true
		return
	elseif IsAddOnLoaded("pMinimap") then
		minimapdb.Square = true
		return
	else
		-- 사각 미니맵 애드온종류 추가시 대비
	end
	minimapdb.Square = false
end
local function MinimapOnEnterfunc(button, t)
	GameTooltip:SetOwner(button, "ANCHOR_TOPLEFT")
	GameTooltip:SetText(t)
end
local function MinimapOnDragfunc(v,s)
	minimapdb.Lock[v] = minimapdb.Lock[v] or false
	if minimapdb.Lock[v] == false then
		if (s == true) then
			getglobal(v):LockHighlight()
			getglobal(v.."Frame"):Show()
		else
			getglobal(v):UnlockHighlight()
			getglobal(v.."Frame"):Hide()
		end
	end
end
local function MinimapPosition(v, p)
	local x,y
	if minimapdb.Square == true then
		x = math.max(-MinimapOutline, math.min(110 * cos(p) ,MinimapOutline))
		y = math.max(-MinimapOutline, math.min(110 * sin(p) ,MinimapOutline))
	else
		x = MinimapOutline * cos(p)
		y = MinimapOutline * sin(p)
	end
	Tools_SetPoint(v, 7, Minimap, 7, 52-x, y-52)
end
local function MinimapOnUpdatefunc(v)
	local xpos, ypos = GetCursorPosition()
	local xmin, ymin = Minimap:GetLeft(), Minimap:GetBottom()
	xpos = xmin - xpos / UIParent:GetScale() + 70
	ypos = ypos / UIParent:GetScale() - ymin - 70
	local value = math.deg(math.atan2(ypos, xpos))
	minimapdb.IconPos[v] = value + ((value < 0) and 360 or 0)
	CheckMinimapAddons()
	MinimapPosition(v, minimapdb.IconPos[v])
end
function CreateMinimapButton(v)
	chkdb()

	minimapdb.Hide = minimapdb.Hide or {}
	minimapdb.IconPos[v.name] = minimapdb.IconPos[v.name] or 0
	minimapdb.Hide[v.name] = minimapdb.Hide[v.name] or nil

	local button = CreateFrame("Button", v.name, Minimap, "ToolsMinimapButtonTemplate")
	local frame = CreateFrame("Frame", v.name.."Frame", button)
	frame:Hide()

	getglobal(v.name.."Icon"):SetTexture(v.texture)

	button:SetScript("OnEnter", function () MinimapOnEnterfunc(button, v.tooltip) end)
	button:SetScript("OnLeave", function () GameTooltip:Hide() end)
	button:SetScript("OnDragStart", function () MinimapOnDragfunc(v.name, true) end)
	button:SetScript("OnDragStop", function () MinimapOnDragfunc(v.name, false) end)
	getglobal(button:GetName().."Frame"):SetScript("OnUpdate", function () MinimapOnUpdatefunc(v.name) end)

	if (v.script) then
		for script, func in pairs(v.script) do
			button:SetScript(script, func)
		end
	end

	MinimapPosition(button, minimapdb.IconPos[v.name])

	if not (minimapdb.Hide[v.name]) then
		getglobal(v.name):Show()
	else
		getglobal(v.name):Hide()
	end
end
-- 이벤트 추가 ( 플레이어 접속완료후 미니맵 아이콘 위치 설정 부분 )
commonframe:RegisterEvent("PLAYER_ENTERING_WORLD")
commonframe:RegisterEvent("ADDON_LOADED")
commonframe:SetScript("OnEvent", function()
	if event == "PLAYER_ENTERING_WORLD" then
		this:UnregisterEvent(event)
		chkdb()
		CheckMinimapAddons()
		for k,v in pairs(minimapdb.IconPos) do
			if (k.ClearAllPoints) then
				MinimapPosition(k, v)
			end
		end
	elseif event == "ADDON_LOADED" and arg1 == "Tools" then
		this:UnregisterEvent(event)
		ToolsDropdownReg({first = {
					{	text = "옵션창열기", notCheckable = 1,
						func = function()
							local v = LoadAddOn("ToolsOption")
							if v then
								ToolsOptionFrame:Show()
							else
								UIErrorsFrame:AddMessage("Tool's Option이 설치되어 있지 않습니다", 1,0,0,1)
							end
						end
				}}})
	end
end)
function ToolsMinimap_Toggle(button)
	if (minimapdb.Hide[button] == true) then
		minimapdb.Hide[button] = nil
		getglobal(button):Show()
	else
		minimapdb.Hide[button] = true
		getglobal(button):Hide()
	end
end
-------------------------------------------------------------------------------------■[ 이벤트 ]
function ToolsEventReg(frame, e, func)
	local f = getglobal(frame) or CreateFrame("Frame", frame)
	if type(e) == "table" then
	    for i = 1, getn(e) do
		f:RegisterEvent(e[i])
	    end
	else
	    f:RegisterEvent(e)
	end
	f:SetScript("OnEvent", function() func(event) end)
end
-------------------------------------------------------------------------------------■[ 타이머 ]
commonframe:SetScript("OnUpdate",
	function ()
		for k,v in pairs(tmpTimerData) do
			if (v.endtime <= GetTime()) then
				tmpTimerData[k] = nil
				if (v.func) then
					v.value = v.value or nil
					return v.func(v.value)
				else
					return true
	end	end	end	end)
-- @ 타이머 배치 실행
local function TimerBatch(head, v)
	local info, looptimes, loopvalues
	if ( type(v.time) == "table" ) then looptimes = v.time end
	if ( type(v.value) == "table" ) then loopvalues = v.value end
	if ( looptimes ) then
		local pretime = 0
		for i=1, table.getn(looptimes) do
			info = {}
			if ( loopvalues ) then
				info.value = loopvalues[i]
			else
				info.value = v.value
			end
			info.func = v.func or nil
			pretime = pretime + looptimes[i]
			info.time = pretime
			ToolsTimer(head..i, info)
		end
	elseif ( loopvalues ) then
		local looptime = v.time
		for i=1, table.getn(loopvalues) do
			info = {}
			info.time = looptime*i
			info.func = v.func or nil
			info.value = loopvalues[i]
			ToolsTimer(head..i, info)
		end
	end
end
-- @ 등록
function ToolsTimer(head, v)
	if ( type(v.time) == "table" ) or ( type(v.value) == "table" ) then
		TimerBatch(head, v)
	else
		v.endtime = GetTime()+v.time
		tmpTimerData[head] = v
	end
end
-------------------------------------------------------------------------------------■[드롭다운]
-- @ 공통 미니맵 확인
local function CheckToolBox()
	if not (ToolsMinimap) and not IsAddOnLoaded("ToolsSquareMinimap") then
		CreateMinimapButton({
			name = "ToolsMinimap",
			texture = "Interface\\Icons\\INV_Crate_01.blp",
			tooltip = "연장상자",
			script={OnClick = function ()
					ToolsDropdownOnClick("Common", ToolsMinimap)
				end}
		})
	end
end
-- @ 드롭다운 메뉴 레벨 설정
local function DropdownInit()
	if not ( ToolsDropdown[Dropdown][UIDROPDOWNMENU_MENU_LEVEL] ) then
		return
	end
	for i = 1, table.getn(ToolsDropdown[Dropdown][UIDROPDOWNMENU_MENU_LEVEL]) do
		local info = ToolsDropdown[Dropdown][UIDROPDOWNMENU_MENU_LEVEL][i]
		if (info.Check) then info.checked = info.checkedfunc(info.Check) end
		if (info.Text) then info.text= info.textfunc(info.Text) end
		if ( UIDROPDOWNMENU_MENU_LEVEL > 1 ) then
			if ( UIDROPDOWNMENU_MENU_VALUE == info.owner) then
				UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL)
			end
		else
			UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL)
		end
	end
	return
end
-- @ 연장상자에 등록
local leveltext = {"first","second","third"}

function ToolsDropdownReg(v)
	CheckToolBox()
	for lv = 1, 3 do
		if (v[leveltext[lv]]) then
			for i = 1, table.getn(v[leveltext[lv]]) do
				tinsert(ToolsDropdown.Common[lv], v[leveltext[lv]][i])
			end
		end
	end
end

function ToolsDropdownRemove(value)
	for lv = 1, 3 do
		for i = 1, table.getn(ToolsDropdown.Common[lv]) do
			if ToolsDropdown.Common[lv][i].value == value then
				tremove(ToolsDropdown.Common[lv], i)
			end
		end
	end
end

function ToolsDropdownOnClick(frame, relativeTo, point, x, y)
	if not getglobal(frame.."Dropdownframe") then
		CreateFrame("Frame", frame.."Dropdownframe", UIParent, "UIDropDownMenuTemplate")
		getglobal(frame.."Dropdownframe"):Hide()
	end
	if (Dropdown) then
		if (Dropdown == frame) and (DropDownList1:IsShown()) then
			getglobal(frame.."Dropdownframe"):Hide()
			CloseDropDownMenus()
			return
		else
			getglobal(Dropdown.."Dropdownframe"):Hide()
		end
	end
	Dropdown = frame
	local info = getglobal(frame.."Dropdownframe")
	info.relativeTo = relativeTo
	info.relativePoint = point or "BOTTOMLEFT"
	info.xOffset= x or 0
	info.yOffset= y or 0

	UIDropDownMenu_Initialize(info, DropdownInit, "MENU");
	ToggleDropDownMenu(1, nil, info)
	getglobal(frame.."Dropdownframe"):Show()
end
