
local lib = Nurfed_General:New();
local utility = Nurfed_Utility:New();
local unitlib = Nurfed_Units:New();

local Original_ChatFrame_OnEvent;

NURFED_SAVED_GENERAL = {};
local saved = nil;
local player = nil;
local version = "12.15.2005";
local currtime = 0;
local checks = {};
local sliders = {};

DAMAGE_TEXT_FONT = "Fonts\\skurri.ttf";

function Nurfed_General_OnLoad()
	this.update = 0;
	this.lastmin = 0;
	this:RegisterEvent("PLAYER_LOGIN");
	this:RegisterEvent("MERCHANT_SHOW");
	this:RegisterEvent("MINIMAP_PING");
	this:RegisterEvent("TRAINER_SHOW");
	this:RegisterEvent("ADDON_LOADED");

	--Hooks
	Original_ChatFrame_OnEvent = ChatFrame_OnEvent;
	ChatFrame_OnEvent = Nurfed_ChatFrame_OnEvent;

	SecondsToTimeAbbrev = Nurfed_SecondsToTimeAbbrev;

	UnitPopupButtons["INSPECT"] = { text = TEXT(INSPECT), dist = 0 };

	--Slash Commands
	SLASH_NURFEDEQUIP1 = "/nequip";
	SlashCmdList["NURFEDEQUIP"] = function( msg )
		Nurfed_Equip_SlashCommandHandler( msg );
	end

	SLASH_NURFEDUSE1 = "/nuse";
	SlashCmdList["NURFEDUSE"] = function( msg )
		Nurfed_Use_SlashCommandHandler( msg );
	end
end

function Nurfed_General_OnEvent(event)
	if (event == "PLAYER_LOGIN") then
		this:UnregisterEvent(event);
		player = UnitName("player").." - "..GetRealmName();

		if (not NURFED_SAVED_GENERAL[player]) then
			NURFED_SAVED_GENERAL[player] = utility:TableCopy(lib.Default);
		end
		Nurfed_General_Init();
		return;
	end

	if (event == "MERCHANT_SHOW") then
		if (saved.repair == 1) then
			lib:repair(saved.repairlimit, saved.repairinv);
		end
		return;
	end

	if (event == "MINIMAP_PING") then
		if(saved.ping == 1) then
			local name = UnitName(arg1);
			if (name ~= UnitName("player")) then
				DEFAULT_CHAT_FRAME:AddMessage((name.." "..NURFEDPING), 1, 1, 0);
			end
		end
		return;
	end

	if (event == "TRAINER_SHOW") then
		if(saved.traineravailable == 1) then
			SetTrainerServiceTypeFilter("unavailable",0);
		end
		return;
	end

	if (event == "ADDON_LOADED" and arg1 == "Blizzard_InspectUI") then
		InspectPaperDollFrame:SetScript("OnShow", Nurfed_InspectOnShow);
	end
end

-- adds guild info to a line in the inspect frame
function Nurfed_InspectOnShow()
	InspectPaperDollFrame_OnShow();
	local guildname, guildtitle = GetGuildInfo("target");
	if(guildname and guildtitle) then
		InspectTitleText:SetText(format(TEXT(GUILD_TITLE_TEMPLATE), guildtitle, guildname));
		InspectTitleText:Show();
	else
		InspectTitleText:Hide();
	end
end

function Nurfed_GeneralOptions_Reset()
	NURFED_SAVED_GENERAL[player] = nil;
	NURFED_SAVED_GENERAL[player] = utility:TableCopy(lib.Default);
	Nurfed_General_Init();
end

function Nurfed_General_OnUpdate(arg1)
	this.update = this.update + arg1;
	if (this.update > 0.5) then
		local hour, minute = GetGameTime();
		if (minute ~= this.lastmin) then
			currtime = GetTime();
			this.lastmin = minute;
		end

		local svol = GetCVar("MasterVolume")+0;
		if (svol > 0.5) then
			SetCVar("MasterVolume", svol-0.05);
		else
			SetCVar("MasterVolume", svol+0.05);
		end
		SetCVar("MasterVolume", svol);
	end
end

function Nurfed_SecondsToTimeAbbrev(seconds)
	local time = "";
	local tempTime;
	local tempTime2;
	if ( seconds > 86400  ) then
		tempTime = ceil(seconds / 86400);
		time = tempTime.." "..DAY_ONELETTER_ABBR;
		return time;
	end
	if ( seconds > 3600  ) then
		tempTime = ceil(seconds / 3600);
		time = tempTime.." "..HOUR_ONELETTER_ABBR;
		return time;
	end
	if ( seconds > 60  ) then
		tempTime = floor(seconds / 60);
		tempTime2 = floor(seconds-(tempTime)*60);
		time = format("%02d:%02d", tempTime, tempTime2);
		return time;
	end
	time = format("00:%02d", seconds);
	return time;
end

function Nurfed_General_Init()
	saved = NURFED_SAVED_GENERAL[player];
	lib:updatemount();
	Nurfed_UpdateManaTableColor();
end

function Nurfed_UpdateManaTableColor()
	if (saved.manacolor == 1) then
		ManaBarColor[0] = { r = 0.00, g = 1.00, b = 1.00, prefix = TEXT(MANA) };
	else
		ManaBarColor[0] = { r = 0.00, g = 0.00, b = 1.00, prefix = TEXT(MANA) };
	end
	UnitFrame_UpdateManaType(PlayerFrame);
	UnitFrame_UpdateManaType(TargetFrame);
	UnitFrame_UpdateManaType(PartyMemberFrame1);
	UnitFrame_UpdateManaType(PartyMemberFrame2);
	UnitFrame_UpdateManaType(PartyMemberFrame3);
	UnitFrame_UpdateManaType(PartyMemberFrame4);
end

function Nurfed_Mount()
	local bag, slot = lib:getmount();
	if (bag and slot) then
		UseContainerItem(bag, slot);
	end
end

function Nurfed_ChatFrame_OnEvent(event)
	if ((event == "CHAT_MSG_SYSTEM") and (arg1 ~= nil)) then
		local _, _, name, id, days, hours, minutes, seconds = string.find(arg1, "(.+) %(ID=(%x+)%): (%d+)d (%d+)h (%d+)m (%d+)s")
		if (name ~= nil) then
			local timeTable = date("*t");
			timeTable["sec"] = timeTable["sec"] + (days * 86400) + (hours * 3600) + (minutes * 60) + seconds;
			arg1 = name.." (ID="..id.."): "..date("%A %B %d at %I:%M %p", time(timeTable)).."";
		end
	end

	Original_ChatFrame_OnEvent(event);
	if(not this.Original_AddMessage) then
		this.Original_AddMessage = this.AddMessage;
		this.AddMessage = Nurfed_AddMessage;
	end
end

function Nurfed_AddMessage(this, msg, r, g, b, id)
	local text = "";

	if msg == nil then msg="The value was nil"; end

	if(saved and saved.timestamps == 1) then
		local hour, minute = GetGameTime();
		local second = GetTime() - currtime;
		hour = hour + saved.timeoffset;
		if( hour > 23 ) then
			hour = hour - 24;
		elseif( hour < 0 ) then
			hour = 24 + hour;
		end
		if (saved.ampm ~= 1) then
			if (hour >= 12) then
				hour = hour - 12;
			end
			if (hour == 0) then
				hour = 12;
			end
		end
		local timestamp = format("%d:%02d:%02d", hour, minute, second);
		text = "["..timestamp.."] ";
	end

	if (saved and string.find(msg, "%[Raid%]") and (saved.raidgroup == 1 or saved.raidclass == 1)) then
		local subgroup, class = unitlib:Raid(arg2);
		if (subgroup and saved.raidgroup == 1) then
			text = text.."["..subgroup.."] ";
		end
		if (class and saved.raidclass == 1) then
			text = text.."["..class.."] ";
		end
	end

	if (text ~= "") then
		local newmsg = text..msg;
		this:Original_AddMessage(newmsg, r, g, b, id);
	else
		this:Original_AddMessage(msg, r, g, b, id);
	end
end

function Nurfed_Equip_SlashCommandHandler( msg )
	if (msg ~= "" and msg ~="help") then
		local itemslot = gsub(msg, "%s*([^%s]+).*", "%1");
		local itemname = gsub(msg, "%s*([^%s]+)%s*(.*)", "%2");
		local itemslotnum = lib.slot[itemslot];
		if ( itemslotnum ) then
			lib:itemswitch(itemname, itemslotnum);
		else
			lib:itemswitch(msg);
		end
	else
		local index = 0;
		local value = getglobal("NURFED_EQUIP_HELP_TEXT"..index);
		while( value ) do
			DEFAULT_CHAT_FRAME:AddMessage(value);
			index = index + 1;
			value = getglobal("NURFED_EQUIP_HELP_TEXT"..index);
		end
	end
end

function Nurfed_Use_SlashCommandHandler(msg)
	if (msg ~= "" and msg ~="help") then
		local slot = lib.slot[msg];
		if (slot) then
			UseInventoryItem(slot);
			SpellStopCasting();
		end
	else
		local index = 0;
		local value = getglobal("NURFED_USE_HELP_TEXT"..index);
		while( value ) do
			DEFAULT_CHAT_FRAME:AddMessage(value);
			index = index + 1;
			value = getglobal("NURFED_USE_HELP_TEXT"..index);
		end
	end
end

function Nurfed_GeneralOptions_OnShow()
	this:SetHeight(200);
	this:SetWidth(300);
	Nurfed_GeneralOptionsFrame:SetHeight(170);
	Nurfed_GeneralOptionsFrame:SetWidth(292);
	Nurfed_GeneralOptionsFrameHeadline:SetText("Nurfed General - "..version);
end

function Nurfed_GeneralOptionsInit()
	checks = {
		[1] = { name = "Auto Repair", option = "repair" },
		[2] = { name = "Auto Repair Inventory", option = "repairinv" },
		[3] = { name = "Ping Warning", option = "ping", },
		[4] = { name = "Only Available Training", option = "traineravailable", },
		[5] = { name = "Chat Timestamps", option = "timestamps" },
		[6] = { name = "24 Hour Timestamps", option = "ampm" },
		[7] = { name = "Chat Raid Group", option = "raidgroup", align = "right" },
		[8] = { name = "Chat Raid Class", option = "raidclass", align = "right" },
		[9] = { name = "Nurfed Mana Color", option = "manacolor", align = "right", func = Nurfed_UpdateManaTableColor },
	};

	sliders = {
		[1] = { name = "Auto Repair Limit", option = "repairlimit", min = 0, max = 150, step = 1 },
		[2] = { name = "Timestamps Offset", option = "timeoffset", min = -12, max = 12, step = 1 },
	};
end

function Nurfed_GeneralOptionsFrameCheckOnShow()
	local id = this:GetID();
	local text = getglobal(this:GetName().."Text");
	local value = saved[checks[id].option];
	local align = checks[id].align;
	if (align == "right") then
		text:ClearAllPoints();
		text:SetPoint("RIGHT", this:GetName(), "LEFT", 0, 0);
	end
	text:SetText(checks[id].name);
	if (value == 1) then
		text:SetTextColor(0,1,0);
	else
		text:SetTextColor(1,0,0);
	end
	this:SetChecked(value);
end

function Nurfed_GeneralOptionsFrameCheckOnClick()
	local id = this:GetID();
	local text = getglobal(this:GetName().."Text");
	local func = checks[id].func;
	if (this:GetChecked() == 1) then
		text:SetTextColor(0,1,0);
	else
		text:SetTextColor(1,0,0);
	end
	saved[checks[id].option] = this:GetChecked();
	if (func) then
		func();
	end
end

function Nurfed_GeneralOptionsFrameSliderOnShow()
	local id = this:GetID();
	local text = getglobal(this:GetName().."Text");
	local minLabel = getglobal(this:GetName().."Low");
	local maxLabel = getglobal(this:GetName().."High");
	text:SetTextColor(0,1,0);
	text:SetText(sliders[id].name);
	minLabel:SetText(sliders[id].min);
	maxLabel:SetText(sliders[id].max);
	this:SetMinMaxValues(sliders[id].min, sliders[id].max);
	this:SetValueStep(sliders[id].step);
	this:SetValue(saved[sliders[id].option]);
end

function Nurfed_GeneralOptionsFrameSliderOnValueChanged()
	local id = this:GetID();
	local text = getglobal(this:GetName().."Value");
	local value = this:GetValue();
	text:SetText("("..value..")");
	text:ClearAllPoints();
	if (this:GetValue() < ((sliders[id].max - sliders[id].min) / 4) + sliders[id].min) then
		text:SetPoint("LEFT", this:GetName().."Thumb", "RIGHT", -6, 0);
	else
		text:SetPoint("RIGHT", this:GetName().."Thumb", "LEFT", 6, 0);
	end
	local option = sliders[id].option;
	saved[option] = this:GetValue();
end

function Nurfed_General_Config()
	if (Nurfed_GeneralOptions:IsVisible()) then
		HideUIPanel(Nurfed_GeneralOptions);
	else
		ShowUIPanel(Nurfed_GeneralOptions);
	end
end
