sUnitFrames_enable = true;
sUnitFrames_info = {name="SmartUnitFrame(SUF)", ver="2.3.0.beta"}

SMART_BUFFDEBUFF_POSITION = {x=5,y=32};

CreateFrame("Frame","SmartUnitFrame", UIParent);
SmartUnitFrame:RegisterEvent("VARIABLES_LOADED")
SmartUnitFrame:RegisterEvent("PLAYER_REGEN_ENABLED")
SmartUnitFrame:SetScript("OnEvent", function() SmartUnitFrame_StartUp(event) end);

CreateFrame("Button","SmartPlayerRelocator", PlayerFrame);
SmartPlayerRelocator:SetFrameLevel(PlayerFrame:GetFrameLevel()+2);
SmartPlayerRelocator:SetFrameStrata("HIGH");
SmartPlayerRelocator:SetPoint("CENTER",PlayerName,"CENTER");
SmartPlayerRelocator:SetWidth(TargetFrameNameBackground:GetWidth());
SmartPlayerRelocator:SetHeight(TargetFrameNameBackground:GetHeight());
SmartPlayerRelocator:SetHitRectInsets(0,0,0,0);
SmartPlayerRelocator:SetScript("OnEnter",function()	SmartUnitFrame_DragEnter() end);
SmartPlayerRelocator:SetScript("OnLeave",function()	SmartUnitFrame_DragLeave() end);
SmartPlayerRelocator:SetScript("OnMouseDown",function()	SmartUnitFrame_DragStart(arg1) end);
SmartPlayerRelocator:SetScript("OnMouseUp",function() SmartUnitFrame_DragStop() end);

CreateFrame("Button","SmartTargetRelocator", TargetFrame);
SmartTargetRelocator:SetFrameLevel(TargetFrame:GetFrameLevel()+2);
SmartTargetRelocator:SetFrameStrata("HIGH");
SmartTargetRelocator:SetPoint("TOPLEFT",TargetFrameNameBackground,"TOPLEFT");
SmartTargetRelocator:SetPoint("BOTTOMRIGHT",TargetFrameNameBackground,"BOTTOMRIGHT");
SmartTargetRelocator:SetHitRectInsets(0,0,0,0);
SmartTargetRelocator:SetScript("OnEnter",function()	SmartUnitFrame_DragEnter() end);
SmartTargetRelocator:SetScript("OnLeave",function()	SmartUnitFrame_DragLeave() end);
SmartTargetRelocator:SetScript("OnMouseDown",function()	SmartUnitFrame_DragStart(arg1) end);
SmartTargetRelocator:SetScript("OnMouseUp",function() SmartUnitFrame_DragStop() end);

local frame

for id=1, MAX_PARTY_MEMBERS do
	frame = CreateFrame("Button", "SmartParty"..id.."Relocator", getglobal("PartyMemberFrame"..id));
	frame:SetFrameLevel(getglobal("PartyMemberFrame"..id):GetFrameLevel()+2);
	frame:SetFrameStrata("HIGH");
	frame:SetPoint("TOPLEFT",getglobal("PartyMemberFrame"..id.."Name"),"TOPLEFT");
	frame:SetPoint("BOTTOMRIGHT",getglobal("PartyMemberFrame"..id.."Name"),"BOTTOMRIGHT");
	frame:SetHitRectInsets(0,0,0,0);
	frame:SetScript("OnEnter",function() SmartUnitFrame_DragEnter() end);
	frame:SetScript("OnLeave",function() SmartUnitFrame_DragLeave() end);
	frame:SetScript("OnMouseDown",function() SmartUnitFrame_DragStart(arg1) end);
	frame:SetScript("OnMouseUp",function() SmartUnitFrame_DragStop() end);

	frame = CreateFrame("Button", "SmartPartyTarget"..id.."Relocator", getglobal("PartyTargetFrame"..id));
	frame:SetFrameLevel(getglobal("PartyTargetFrame"..id):GetFrameLevel()+2);
	frame:SetFrameStrata("HIGH");
	frame:SetPoint("TOPLEFT",getglobal("PartyTargetFrame"..id.."Name"),"TOPLEFT");
	frame:SetPoint("BOTTOMRIGHT",getglobal("PartyTargetFrame"..id.."Name"),"BOTTOMRIGHT");
	frame:SetHitRectInsets(0,0,0,0);
	frame:SetScript("OnEnter",function() SmartUnitFrame_DragEnter() end);
	frame:SetScript("OnLeave",function() SmartUnitFrame_DragLeave() end);
	frame:SetScript("OnMouseDown",function() SmartUnitFrame_DragStart(arg1) end);
	frame:SetScript("OnMouseUp",function() SmartUnitFrame_DragStop() end);
end

function NewTargetFrame_OnUpdate()
end

function NewTargetofTarget_Update()
end

function NewTargetofTarget_OnUpdate(elapsed)
end

-- CHECK ADDON_BLOCKED
-- local f = CreateFrame("Frame","SmartAddonsBlockCheckTestFrame");
-- f:SetScript("OnEvent",function() DEFAULT_CHAT_FRAME:AddMessage("BLOCKED: "..tostring(arg1)..", "..tostring(arg2)) end);
-- f:RegisterEvent("ADDON_ACTION_BLOCKED");
function SmartUnitFrame_StartUp(event)
	if (event == "VARIABLES_LOADED") then
		SmartUnitFrame_MovableCheck();
		SlashCmdList["SUF"] = SmartUnitFrame_CmdHandler;
		SLASH_SUF1 = "/suf";
		UnitFrame_Update = SmartUnitFrame_UnitFrame_Update;
		TargetFrame_OnUpdate = NewTargetFrame_OnUpdate;
		TargetofTarget_Update = NewTargetofTarget_Update;
		TargetofTarget_OnUpdate = NewTargetofTarget_OnUpdate;

		DEFAULT_CHAT_FRAME:AddMessage(sUnitFrames_info.name.." v"..sUnitFrames_info.ver.." (명령어 : /suf)", 1,0.82,0);

		if SCONFIG_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   CONFIG.UI Loaded", 1,0.82,0);
		end

		if SMART_BUFFDEBUFF_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   BUFF/DEBUFF Loaded", 1,0.82,0);
		end

		if SMART_FOCUS_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   FOCUS Loaded", 1,0.82,0);
		end

		if SMART_SKIN_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   SKIN - "..SMART_SKIN_NAME.." Loaded", 1,0.82,0);
		end

		if SMART_SETSCALE_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   SET.SCALE Loaded", 1,0.82,0);
		end

		if SMART_GROUPICON_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   GROUP.ICON Loaded", 1,0.82,0);
		end

		if SMART_CLASSICON_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   CLASS.ICON Loaded", 1,0.82,0);
		end

		if SMART_PVPICON_ENABLE then
			DEFAULT_CHAT_FRAME:AddMessage("   PVP.ICON Loaded", 1,0.82,0);
		end

		-- 본래 블리자드 FrameXML에서 생명력에 따라 바색깔을 바꾸는 코드가 있지만,
		-- 잘못된 호출 순서에 의해 작동되지 않고 있다. 07.11.24 - Isidur
		
		-- 원래 UnitFrameHealthBar_OnValueChanged 함수에서 HealthBar_OnValueChanged를 불러
		-- 색을 바꾸려고 하지만 바뀌지 않으므로 HealthBar_OnValueChanged를 없앤 코드로 대체한다
		UnitFrameHealthBar_OnValueChanged = function() TextStatusBar_OnValueChanged() end

		-- UnitFrameHealthBar_Update이 호출될 때 SmartUnitFrame_SetHealthBarColor가 호출되도록 후킹
		hooksecurefunc("UnitFrameHealthBar_Update", function(healthbar) SmartUnitFrame_SetHealthBarColor(healthbar) end)
	elseif (event == "PLAYER_REGEN_ENABLED") then
		if UnitInParty("player") or UnitInRaid("player") then
			if GetNumPartyMembers() > 0 then
				RaidOptionsFrame_UpdatePartyFrames()
			end
		end
	end
end

function SmartUnitFrame_UnitFrame_Update()
	local nameServer;

	if (this.unit == "party1") or (this.unit == "party2") or (this.unit == "party3") or (this.unit == "party4") then
		nameServer = SMART_PARTY_Config.namewithserver;
	end

	this.name:SetText(GetUnitName(this.unit, nameServer))
	SetPortraitTexture(this.portrait, this.unit)
	UnitFrameHealthBar_Update(this.healthbar, this.unit)
	UnitFrameManaBar_Update(this.manabar, this.unit)
end

function SmartUnitFrame_SetHealthBarColor(bar)
	local r, g, b;
	local value = bar:GetValue();
	local min, max = bar:GetMinMaxValues();

	if ((value < min) or (value > max) ) then
		return;
	end
	if ( (max - min) > 0 ) then
		value = (value - min) / (max - min);
	else
		value = 0;
	end

	if (value > 0.5) then
		r = (1.0 - value) * 2;
		g = 1.0;
	else
		r = 1.0;
		g = value * 2;
	end

	b = 0.0;

	bar:SetStatusBarColor(r, g, b);
end

function SmartUnitFrame_CmdHandler(msg)
	if (strlower(msg) == strlower("reset")) then
		SmartUnitFrame_Reset();
	elseif (strlower(msg) == strlower("reseticon")) then
		if SCONFIG_ENABLE then
			SmartConfigUI_CommandHandler("reseticon");
		else
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: 미니맵 아이콘 사용불가", 1,0.5,0);
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: SmartConfigUI가 필요합니다.", 1,0.5,0);
		end
	elseif (strlower(msg) == strlower("config")) then
		if SCONFIG_ENABLE then
			SmartConfigUI_OpenConfig();
		else
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: 유닛프레임 설정 사용불가", 1,0.5,0);
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: SmartConfigUI가 필요합니다.", 1,0.5,0);
		end
	elseif (strlower(msg) == strlower("resetconfig")) then
		if SCONFIG_ENABLE then
			SmartConfigUI_ResetConfig();
		else
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: 유닛프레임 설정 사용불가", 1,0.5,0);
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: SmartConfigUI가 필요합니다.", 1,0.5,0);
		end
	elseif (strlower(msg) == strlower("scale")) then
		if SMART_SETSCALE_ENABLE then
			SmartSetScale_ToggleMenu()
		else
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: 유닛프레임 크기설정 사용불가", 1,0.5,0);
			DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: SmartSetScale이 필요합니다.", 1,0.5,0);
		end
	else
		DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame Command: /suf", 1,1,1);
		DEFAULT_CHAT_FRAME:AddMessage("[ reset | reseticon | config | resetconfig | scale ]", 1,1,1);
		DEFAULT_CHAT_FRAME:AddMessage("▤ reset - 유닛프레임 위치초기화",0.75,0.75,0.75);
		DEFAULT_CHAT_FRAME:AddMessage("▤ reseticon - 미니맵아이콘 위치초기화",0.75,0.75,0.75);
		DEFAULT_CHAT_FRAME:AddMessage("▤ config - 유닛프레임 설정창 열기/닫기",0.75,0.75,0.75);
		DEFAULT_CHAT_FRAME:AddMessage("▤ resetconfig - 유닛프레임 설정초기화",0.75,0.75,0.75);
		DEFAULT_CHAT_FRAME:AddMessage("▤ scale - 유닛프레임 크기설정창 열기/닫기",0.75,0.75,0.75);
	end
end

function SmartUnitFrame_Reset()
	SmartPlayer_ResetPosition()
	SmartTarget_ResetPosition()
	SmartParty_ResetPosition()
	SmartParty_GroupCheck(true)
	SmartToT_ResetPosition()
	SmartPartyTarget_ResetPosition(true)

	if SMART_FOCUS_ENABLE then
		SmartFocus_ResetPosition()
	end

	DEFAULT_CHAT_FRAME:AddMessage("SmartUnitFrame: 모든 유닛프레임 위치초기화", 1,0.5,0);
end

function SmartUnitFrame_MovableLock()
	SmartPlayerRelocator.movable = false;
	SmartTargetRelocator.movable = false;

	local i
	for i=1, MAX_PARTY_MEMBERS do
		getgloba("SmartParty"..i.."Relocator").movable = false
		getgloba("SmartPartyTarget"..i.."Relocator").movable = false
	end
end

function SmartUnitFrame_MovableCheck()
	if SMART_PLAYER_Config.movable then
		SmartPlayerRelocator.movable = true;
		SmartPlayerRelocator:Show();
	else
		SmartPlayerRelocator.movable = false;
		SmartPlayerRelocator:Hide();
	end

	if SMART_TARGET_Config.movable then
		SmartTargetRelocator.movable = true;
		SmartTargetRelocator:Show();
	else
		SmartTargetRelocator.movable = false;
		SmartTargetRelocator:Hide();
	end

	local frame
	local i
	for i=1, MAX_PARTY_MEMBERS do
		frame = getglobal("SmartParty"..i.."Relocator")

		if i == 1 then
			frame.movable = SMART_PARTY_Config.movable
		else
			frame.movable = SMART_PARTY_Config.movablegroup and SMART_PARTY_Config.movable
		end

		if frame.movable then
			frame:Show()
		else
			frame:Hide()
		end
	end

	for i=1, MAX_PARTY_MEMBERS do
		frame = getglobal("SmartPartyTarget"..i.."Relocator")

		frame.movable = SMART_PARTY_Config.movable

		if frame.movable then
			frame:Show()
		else
			frame:Hide()
		end
	end
end

function SmartUnitFrame_DragEnter()
	if this.movable then
		GameTooltip:SetOwner(this, "ANCHOR_BOTTOMRIGHT");
		GameTooltip:AddLine("프레임 이동가능");
		GameTooltip:AddLine("Alt + 왼쪽 또는 오른쪽 마우스 버튼으로 프레임 이동", 1,1,1);
		GameTooltip:Show();
	end
end

function SmartUnitFrame_DragLeave()
	GameTooltip:Hide()
end

function SmartUnitFrame_DragStart(button)
	if this.movable and IsAltKeyDown() then
		if (button == "LeftButton") or (button == "RightButton") then
			if this:GetParent():IsMovable() then
				this:GetParent():StartMoving()
			end
		end
	end
end

function SmartUnitFrame_DragStop()
	if this:GetParent():IsMovable() then
		this:GetParent():StopMovingOrSizing()
	end
end

