local ADDON_NAME = "BabText";
local ADDON_VER = "1.00";
local ADDON_USAGE = "/babtext";

local NUM_OPTIONS = 5;
local RESET = {0,0,1,1,1};

--local SHOW_EXP = nil;

--local Orig_MainMenuExpBar_OnEnter , BabText_MainMenuExpBar_OnEnter;

------------- Commom functions --------------------------------------------------------------------------
local function Print(msg, r, g, b, frame)
	if (not r) then r = 1.0; end
	if (not g) then g = 1.0; end
	if (not b) then b = 1.0; end
	if ( frame ) then
		if frame=="UIErrorsFrame" then
			UIErrorsFrame:AddMessage(msg,1,0.7,0.7,1,5);
		else
			frame:AddMessage(msg,r,g,b);
		end
	else
		if ( DEFAULT_CHAT_FRAME ) then
			DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b);
		end
	end
end

local function Notice(msg)
	Print(msg, 1,0.7,0.2);
end

local function Error(msg)
	Print(msg, nil, nil, nil, "UIErrorsFrame");
end

local function DB(msg)
	if not msg then
		msg = "Check!"
	end
	Print(msg, 0.5, 0.5, 0.5);
end

local function SetHook(myFunction, HookFunc, reverse)
	local oldFunction = getglobal(HookFunc);
	local newFunction;
	if not reverse then
		newFunction = function(arg1,arg2,arg3,arg4,arg5)
				local r={};
				r[1],r[2],r[3],r[4],r[5] = oldFunction(arg1,arg2,arg3,arg4,arg5);
				myFunction(arg1,arg2,arg3,arg4,arg5);
				if r[1] then
					return r[1],r[2],r[3],r[4],r[5]
				end
		end
	else
		newFunction = function(arg1,arg2,arg3,arg4,arg5)
				local r={};
				r[1] = myFunction(arg1,arg2,arg3,arg4,arg5);
				if r[1] then
					return
				end
				r[1],r[2],r[3],r[4],r[5] = oldFunction(arg1,arg2,arg3,arg4,arg5);
				if r[1] then
					return r[1],r[2],r[3],r[4],r[5]
				end
		end
	end
	setglobal(HookFunc, newFunction);
end

-- Hook ------------------------------------------------------------------------------------------------
function BabText_HealthBar_OnValueChanged(self, value, smooth)
	if this:GetName()=="GameTooltipStatusBar" and BabText_Saved[3] == 1 then 
		if ( not value) then
			return;
		end
		local min, max = this:GetMinMaxValues();
		if ( (value < min) or (value > max) ) then
			return;
		end
		if ( (max - min) > 0 ) then
			BabTextTooltipHealthText:SetText(value.." / "..max);
		end
	end
end

--[[
function BabText_MainMenuExpBar_OnEnter()
	Orig_MainMenuExpBar_OnEnter();
	BabText_OnEvent("PLAYER_XP_UPDATE");
end
]]--

function BabText_ReputationWatchBar_Update(newLevel)
	local name, standing, min, max, value = GetWatchedFactionInfo();
	local standingtext = {[1]="매우 적대적", [2]="약간 적대적", [3]="적대적", [4]="중립적", [5]="약간 우호적", [6]="우호적", [7]="매우 우호적", [8]="확고한 동맹"}
	standing = standingtext[standing];
	max = max - min;
	value = value - min;

	local perc = ceil(value/max*1000)/10;
	local prev_text = ReputationWatchStatusBarText:GetText();
	if prev_text and standing then
		ReputationWatchStatusBarText:SetText(prev_text .. "       " .. standing .. "   " .. perc .."%");
	end
end

function BabText_UnitFrameBar_Update(statusbar, unit)
	if statusbar and unit then
		local bn = statusbar:GetName()
		local bartype;
		local f , fn , ft;
		
		if strfind( bn , "Health" ) then
			bartype = "HealthBar";
		else
			bartype = "ManaBar";
		end
		
		--[[if unit == "player" then
			fn = "PlayerFrame" .. bartype;

		]]
		if unit == "target" and BabText_Saved[1] == 1 then
			fn = "TargetFrame" .. bartype;
		elseif unit == "targettarget" and BabText_Saved[2] == 1 then
			fn = "TargetofTarget" .. bartype;
		else
			return
		end
		f = getglobal(fn);
		ft = getglobal(fn .. "Text");

		if f == statusbar then
			local func1, func2;
			if bartype == "HealthBar" then
				func1 = UnitHealth;
				func2 = UnitHealthMax;
			else
				func1 = UnitMana;
				func2 = UnitManaMax;
			end

			local num = func1(unit);
			local numMax = func2(unit);
			local perc = num;
			if perc == 0 then
				perc = 0
			elseif perc ~= 100 then
				perc = floor(num/numMax*100);
			end
			if perc <= 0 then
				ft:SetText();
			else
				if unit == "player" then
					ft:SetText(num .." / ".. numMax .. "   " .. perc .."%" );					
				elseif unit == "target" then
					if numMax ~= 100 then
						ft:SetText(num .." / ".. numMax);
					else
						ft:SetText(perc.."%");
					end
				else
					ft:SetText(perc.."%");
				end
			end
		end
	end
end
	
--------------------------------------------------------------------------------------------------------
local function BabText_UpdateMouseover()
	if UnitExists("mouseover") and BabText_Saved[4]==1 then
		BabText_UpdateHealthText("mouseover");

		if UnitExists("mouseovertarget") then
			local name = UnitName("mouseovertarget");
			BabTextTooltipMouseoverTargetText:SetText(name);
			if UnitIsUnit("mouseovertarget", "player") then
				if UnitCanAttack("player", "mouseover") then
					BabTextTooltipMouseoverTargetText:SetTextColor(1,0.2,0.2);
				else
					BabTextTooltipMouseoverTargetText:SetTextColor(0.4,1,0.4);
				end
			else
				BabTextTooltipMouseoverTargetText:SetTextColor(0.7,0.7,0.7);
			end
		else
			BabTextTooltipMouseoverTargetText:SetText();
		end
	end
end

function BabText_UpdateHealthText(unit)
	local cur, max;
	cur = UnitHealth(unit);
	max = UnitHealthMax(unit);
	BabTextTooltipHealthText:SetText(cur.." / "..max);
end

--[[
local function BabText_UpdateExp()
	local playerCurrXP = UnitXP("player");
	local playerMaxXP = UnitXPMax("player");
	local per = ceil(playerCurrXP/playerMaxXP*100*10)/10;
	local prev_text = MainMenuBarExpText:GetText();
	if prev_text then
		local num;
		local text = "";
		if BabText.mob and BabText.mobxp then
			num = ceil((playerMaxXP-playerCurrXP)/BabText.mobxp*10)/10;
			text = per.."%      ( ".. BabText.mob .." "..num.." 마리 )";
		else
			text = per.."%";
		end
		MainMenuBarExpText:SetText(prev_text .."       ".. text);
	end
end
]]--

function BabText_ToPet()
	if BabText_Saved[5] == 1 then
		if ( UnitExists("pettarget") ) then
			BabTargetofPetText:SetText(UnitName("pettarget"));
			if ( UnitIsPlayer("pettarget") ) then
				local l,e = UnitClass("pettarget");
				e = string.upper(e);
				local color = RAID_CLASS_COLORS[e];
				BabTargetofPetText:SetTextColor(color.r,color.g,color.b);
			else
				BabTargetofPetText:SetTextColor(.8,.8,1);
			end
			BabTargetofPetHPbar:Show();
			local currValue = UnitHealth("pettarget");
			local maxValue = UnitHealthMax("pettarget");
			local percent_full = currValue / maxValue;
			local rgb = { r = 1, g = 0, b = 0 }
			if (percent_full > .66) then
			  rgb.r = 0
			  rgb.g = 1
			  rgb.b = 0
			elseif (percent_full > .33) then
			  rgb.r = 1
			  rgb.g = 1
			  rgb.b = 0
			end
			BabTargetofPetHPbar:SetStatusBarColor(rgb.r, rgb.g, rgb.b); 
			BabTargetofPetHPbar:SetMinMaxValues(0, maxValue);
			BabTargetofPetHPbar:SetValue(currValue);
		else
			BabTargetofPetHPbar:Hide();
			BabTargetofPetText:SetText(UnitName("pet"));
			BabTargetofPetText:SetTextColor(1,0.82,0);
		end
	end
end
------------- option ----------------------------------------------------------------------------------
local function BabTextToggle(id,arg)
	if arg==1 then
		BabText_Saved[id] = 1;
		if id == 1 then
			BabText_UnitFrameBar_Update(TargetFrameHealthBar, "target");
			BabText_UnitFrameBar_Update(TargetFrameManaBar, "target");
		elseif id == 2 then
			BabText_UnitFrameBar_Update(TargetofTargetHealthBar, "targettarget");
			BabText_UnitFrameBar_Update(TargetofTargetManaBar, "targettarget");
		elseif id == 3 then
			--
		elseif id == 4 then
			BabText_UpdateMouseover();
		elseif id == 5 then
			-- BabText_ToPet();
			PetName:Hide();
			BabTargetofPet:Show();
		end
	else
		BabText_Saved[id] = 0;
		if id == 1 then
			TargetFrameHealthBarText:SetText();
			TargetFrameManaBarText:SetText();
		elseif id == 2 then
			TargetofTargetHealthBarText:SetText();
			TargetofTargetManaBarText:SetText();
		elseif id == 3 then
			BabTextTooltipHealthText:SetText();
		elseif id == 4 then
			BabTextTooltipMouseoverTargetText:SetText();
		elseif id == 5 then
			BabTargetofPetHPbar:Hide();
			BabTargetofPetText:SetText(UnitName("pet"));
			BabTargetofPetText:SetTextColor(1,0.82,0);
			PetName:Show();
			BabTargetofPet:Hide();
		end
	end
end

function BabTextCheckButton_OnClick()
	if (this:GetChecked()) then
		BabTextToggle(this:GetID() , 1);
	else
		BabTextToggle(this:GetID() , 0);
	end
end

function BabTextCheckButton_OnEnter()
	GameTooltip:SetOwner(this, "ANCHOR_RIGHT");
	GameTooltip:SetText(this.tt)
end

function BabTextCheckButton_OnLeave()
	GameTooltip:Hide();
end


local function BabText_Config()
	for i=1,NUM_OPTIONS do
		local f = getglobal("BabTextCheck"..i);
		local ft = getglobal("BabTextCheck"..i.."Text");
		local arg = BabText_Saved[i];
		
		if i == 1 then
			f.text = "타겟프레임 체력/마나 표시";
			f.tt = "대상 창의 체력/마나 표시를 On/Off 합니다.";
		elseif i == 2 then
			f.text = "ToT프레임 체력/마나 표시";
			f.tt = "대상의대상 창의 체력/마나 표시를 On/Off 합니다.";
		elseif i == 3 then
			f.text = "툴팁 체력 표시";
			f.tt = "툴팁의 체력바 수치 표시를 On/Off 합니다.";
		elseif i == 4 then
			f.text = "툴팁 TargetOfMouseover 표시"
			f.tt = "툴팁의대상 표시를 On/Off 합니다.";
		elseif i == 5 then
			f.text = "TargetOfPet 표시"
			f.tt = "펫의대상 표시를 On/Off 합니다.";
		end
		BabTextToggle(i,arg);

		f:SetChecked(arg);
		ft:SetText(f.text);
	end
end

function BabText_Reset()
	for i = 1 ,NUM_OPTIONS do
		BabText_Saved[i] = RESET[i];
	end
	BabText_Config();
	for i = 1 ,NUM_OPTIONS do
		BabTextToggle(i,RESET[i]);
	end
end
--------------------------------------------------------------------------------------------------------
function BabText_SaveMoney()
	local temp = date();
	local Year = "20"..strsub(temp,7,8);
	local Month = strsub(temp,1,2);
	local Day = strsub(temp,4,5);

	BabText_MoneySaved.theDate = Year.."/"..Month.."/"..Day;
	BabText_MoneySaved.theHour = strsub(temp,10,11).."시";
	BabText_MoneySaved.theMin = strsub(temp,13,14).."분";
	BabText_MoneySaved.theTime = time();
	BabText_MoneySaved.theMoney = GetMoney();
	
	Print("현재 시간이후로 손익계산을 시작합니다.",0.4,0.4,1);
end
function BabText_UpdateMoney()
	if BabText_MoneySaved.theDate then
		local date = BabText_MoneySaved.theDate;
		local hour = BabText_MoneySaved.theHour;
		local min = BabText_MoneySaved.theMin;
		local dTime = time() - BabText_MoneySaved.theTime;
		local dDay = floor(dTime/60/60/24);
		local dHour = floor( (dTime-dDay*60*60*24)/60/60 );
		local dMin = floor( (dTime-dDay*60*60*24-dHour*60*60)/60 );
		local dSec = floor( (dTime-dDay*60*60*24-dHour*60*60-dMin*60) );
		local msg = date.." "..hour..min.." 이후 ";
		Print(msg , 0.8 , 0.8 , 0.2);

		if dDay~=0 then
			msg = dDay.."일"..dHour.."시간"..dMin.."분"..dSec.."초 경과";
		elseif dHour~=0 then
			msg = dHour.."시간"..dMin.."분"..dSec.."초 경과";
		elseif dMin~=0 then
			msg = dMin.."분"..dSec.."초 경과";
		else
			msg = dSec.."초 경과";
		end
		Print( msg , 0.5 , 0.5 , 1 );

		local dMoney = GetMoney() - BabText_MoneySaved.theMoney;
		local isMinus;
		if dMoney<0 then
			isMinus=true;
			dMoney = abs(dMoney);
		end
		local gold = floor(dMoney/10000);
		local silver = floor((dMoney-gold*10000)/100);
		local copper = dMoney - gold*10000 - silver*100;
		if gold~=0 then
			msg = LIGHTYELLOW_FONT_COLOR_CODE..gold.."골드 "..GRAY_FONT_COLOR_CODE..silver.."실버 "..NORMAL_FONT_COLOR_CODE..copper.."코퍼";
		elseif silver~=0 then
			msg = GRAY_FONT_COLOR_CODE..silver.."실버 "..NORMAL_FONT_COLOR_CODE..copper.."코퍼";
		elseif copper~=0 then
			msg = NORMAL_FONT_COLOR_CODE..copper.."코퍼";
		end
		if isMinus then
			msg = msg..RED_FONT_COLOR_CODE.." 감소";
		else
			if dMoney==0 then
				msg="손익 변동없음";
			else
				msg=msg..GREEN_FONT_COLOR_CODE.." 증가";
			end
		end
		Print(msg);
	end
end


------------- onFoo functions --------------------------------------------------------------------------
local function BabText_VariablesLoaded()
	--Orig_MainMenuExpBar_OnEnter = MainMenuExpBar:GetScript("OnEnter");
	--MainMenuExpBar:SetScript("OnEnter", BabText_MainMenuExpBar_OnEnter);
	--SetHook(BabText_HealthBar_OnValueChanged, "HealthBar_OnValueChanged");
	--SetHook(BabText_ReputationWatchBar_Update, "ReputationWatchBar_Update");
	--SetHook(BabText_UnitFrameBar_Update, "UnitFrameHealthBar_Update");
	--SetHook(BabText_UnitFrameBar_Update, "UnitFrameManaBar_Update");
	
	if not (BabText_Saved and BabText_MoneySaved) or (BabText_Saved.ver ~= ADDON_VER) or (#BabText_Saved~=NUM_OPTIONS) then
		BabText_Saved = {};
		BabText_Saved.ver = ADDON_VER;
		for i=1,NUM_OPTIONS do
			BabText_Saved[i] = RESET[i];
		end

		BabText_MoneySaved = {["theDate"]=nil,["theHour"]=nil,["theMin"]=nil,["theTime"]=nil,["theMoney"]=nil};
		
	end

	BabText_Config();
end


function BabText_OnLoad()
	this.addon_name = ADDON_NAME;
	this.addon_ver = ADDON_VER;

	this:RegisterEvent("VARIABLES_LOADED");
	this:RegisterEvent("UPDATE_MOUSEOVER_UNIT");
	this:RegisterEvent("PLAYER_ENTERING_WORLD");
	this:RegisterEvent("PLAYER_PVP_RANK_CHANGED");
	--[[
	this:RegisterEvent("CHAT_MSG_COMBAT_XP_GAIN");
	this:RegisterEvent("PLAYER_XP_UPDATE");
	this:RegisterEvent("PLAYER_LEVEL_UP");
	]]--

	--MainMenuBarExpText:SetFont("Fonts\\2002.ttf",12,"OUTLINE");
	ReputationWatchStatusBarText:SetFont("Fonts\\2002.ttf",12,"OUTLINE");


	SlashCmdList["BABTEXT"] = function()
		BabTextOption:Show();
	end

	SLASH_BABTEXT1 = "/babtext";
	SLASH_BABTEXT2 = "/BABTEXT";
end

function BabText_OnEvent(event)
	if event == "VARIABLES_LOADED" then
		Notice(ADDON_NAME.." ver."..ADDON_VER.." Loaded. ( Usage : ".. ADDON_USAGE .. " )");
		BabText_VariablesLoaded();

	elseif event == "UPDATE_MOUSEOVER_UNIT" then
		BabText_UpdateMouseover();

	--[[
	elseif event == "PLAYER_ENTERING_WORLD" then
		BabText_UpdateExp();

	elseif event == "CHAT_MSG_COMBAT_XP_GAIN" then
		for i, j in string.gmatch(arg1, "(.+)|1이;가; 죽었습니다. (.+)의 경험치를 획득했습니다.+") do
			this.mob = i;
			this.mobxp = j;
		end

	elseif event == "PLAYER_XP_UPDATE" then
		BabText_UpdateExp();

	elseif event == "PLAYER_LEVEL_UP" then
		this.mob = nil;
		this.mobxp = nil;
	]]--

	end
end

function BabText_OnUpdate(elapsed)
	BabText_UpdateMouseover();
end



 

