local f = InfoPanel_AddPlugin();
local UPDATE_INTERVAL = 1;
local nextUpdate = 0;
local startTime, endTime, combatTime;

--------------------------------------------------------------------------------------------------------
--                                             Functions                                              --
--------------------------------------------------------------------------------------------------------

-- OnEnter
local function OnEnter(self)
	InfoPanel_MakeTip(f,"Combat Timer");

	if (combatTime) then
		GameTooltip:AddDoubleLine("In Seconds",format("%.3f",combatTime),nil,nil,nil,1,1,1);
	end
	if (startTime) then
		GameTooltip:AddDoubleLine("Start Time",date("%H:%M:%S",time() - GetTime() + startTime),nil,nil,nil,1,1,1);
	end
	if (endTime) then
		GameTooltip:AddDoubleLine("End Time",date("%H:%M:%S",time() - GetTime() + endTime),nil,nil,nil,1,1,1);
		GameTooltip:AddDoubleLine("Time Since",InfoPanel_FormatTime2(GetTime() - endTime),nil,nil,nil,1,1,1);
	end

	GameTooltip:Show();
end

-- OnUpdate
local function OnUpdate(self,elapsed)
	nextUpdate = (nextUpdate - elapsed);
	if (nextUpdate <= 0) then
		combatTime = (GetTime() - startTime);
		InfoPanel_SetText(f,"%.2d:%.2d",floor(combatTime/60),floor(mod(combatTime,60)));
		nextUpdate = UPDATE_INTERVAL;
	end
end

-- OnEvent
local function OnEvent(self,event)
	nextUpdate = 0;
	if (event == "PLAYER_REGEN_DISABLED") then
		f.text:SetTextColor(0/255,255/255,0/255);
		f:SetScript("OnUpdate",OnUpdate);
		startTime = GetTime();
	elseif (event == "PLAYER_REGEN_ENABLED") then
		f.text:SetTextColor(128/255,192/255,255/255);
		f:SetScript("OnUpdate",nil);
		endTime = GetTime();
		OnUpdate(f,0);
	end
end

-- OnClick
local function OnClick(self,button)
	if (ChatFrameEditBox:IsShown()) and (combatTime) then
		ChatFrameEditBox:Insert(format("%d min %.2d sec",floor(combatTime/60),floor(mod(combatTime,60))));
	end
end

--------------------------------------------------------------------------------------------------------
--                                              Finalize                                              --
--------------------------------------------------------------------------------------------------------

f.icon:SetTexture("Interface\\Icons\\Spell_Shadow_LastingAfflictions");
f:SetScript("OnEnter",OnEnter);
f:SetScript("OnEvent",OnEvent);
f:SetScript("OnClick",OnClick);
f:RegisterEvent("PLAYER_REGEN_DISABLED");
f:RegisterEvent("PLAYER_REGEN_ENABLED");
InfoPanel_SetText(f,"00:00");