sUnitFrames_enable = true;
sUnitFrames_info = {name="SmartUnitFrame(SUF)", ver="3.0.2.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(self) SmartUnitFrame_OnEnter(self) end);
SmartPlayerRelocator:SetScript("OnLeave", SmartUnitFrame_OnLeave);
SmartPlayerRelocator:SetScript("OnMouseDown", function(self, arg1) SmartUnitFrame_OnMouseDown(self, arg1) end);
SmartPlayerRelocator:SetScript("OnMouseUp", function(self) SmartUnitFrame_OnMouseUp(self) 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(self) SmartUnitFrame_OnEnter(self) end);
SmartTargetRelocator:SetScript("OnLeave", SmartUnitFrame_OnLeave);
SmartTargetRelocator:SetScript("OnMouseDown", function(self, arg1) SmartUnitFrame_OnMouseDown(self, arg1) end);
SmartTargetRelocator:SetScript("OnMouseUp", function(self) SmartUnitFrame_OnMouseUp(self) 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(self) SmartUnitFrame_OnEnter(self) end);
	frame:SetScript("OnLeave", SmartUnitFrame_OnLeave);
	frame:SetScript("OnMouseDown", function(self, arg1) SmartUnitFrame_OnMouseDown(self, arg1) end);
	frame:SetScript("OnMouseUp", function(self) SmartUnitFrame_OnMouseUp(self) 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(self) SmartUnitFrame_OnEnter(self) end);
	frame:SetScript("OnLeave", SmartUnitFrame_OnLeave);
	frame:SetScript("OnMouseDown", function(self, arg1) SmartUnitFrame_OnMouseDown(self, arg1) end);
	frame:SetScript("OnMouseUp", function(self) SmartUnitFrame_OnMouseUp(self) end);
end

function NewTargetFrame_OnUpdate(self)
end

function NewTargetofTarget_Update(self)
end

function NewTargetofTarget_OnUpdate(self, elapsed)
end

function SmartUnitFrame_UnitFrame_Update(self)
	local nameServer;

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

	if (self.overrideName) then
		self.name:SetText(GetUnitName(self.overrideName, nameServer));
	else
		self.name:SetText(GetUnitName(self.unit, nameServer));
	end

	UnitFramePortrait_Update(self);
	UnitFrameHealthBar_Update(self.healthbar, self.unit)
	UnitFrameManaBar_Update(self.manabar, self.unit)
	UnitFrame_UpdateThreatIndicator(self.threatIndicator, self.threatNumericIndicator)
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에서 생명력에 따라 바색깔을 바꾸는 코드가 있지만,
		-- HealthBar_OnValueChanged의 세번째 인자를 넣지 않아 작동되지 않고 있다. 08.10.24 - Isidur
		_HealthBar_OnValueChanged = HealthBar_OnValueChanged
		HealthBar_OnValueChanged = function(self, value)
			_HealthBar_OnValueChanged(self, value, true)
		end

		-- UnitFrameHealthBar_Update이 호출될 때 SmartUnitFrame_SetHealthBarColor가 호출되도록 후킹
		hooksecurefunc("UnitFrameHealthBar_Update", function(bar, unit) HealthBar_OnValueChanged(bar, bar:GetValue()) 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_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;

	if SMART_FOCUS_ENABLE then
		SmartFocusRelocator.movable = false;
	end

	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

	if SMART_FOCUS_ENABLE then
		SmartFocusRelocator.movable = SmartTargetRelocator.movable;
		if SmartTargetRelocator:IsShown() then
			SmartFocusRelocator:Show()
		else
			SmartFocusRelocator:Hide()
		end
	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_OnEnter(self)
	GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT");

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

function SmartUnitFrame_OnLeave()
	GameTooltip:Hide()
end

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

function SmartUnitFrame_OnMouseUp(self)
	self:GetParent():StopMovingOrSizing()
end

