--------------------------------------------------------------------------
-- Scheduler.lua 
--------------------------------------------------------------------------
--[[
Event Scheduling
]]--

function BlindAssist.Schedule(sName, iDelayTime, bCombatOnly, functionEvent, ...)
	local name = sName;
	if not (name) then
		name = tostring(math.random());
	end
	
	local event = { 
		Name = name;
		Time = GetTime() + iDelayTime;
		Script = functionEvent;
		CombatOnly = bCombatOnly;
		Arguments = BlindAssist.Pack(...);
	};
		
	BlindAssist.ClearEvent(name);
	tinsert(BlindAssist.Data.ScheduleQueue, event);
	BlindAssistScheduleFrame:SetScript("OnUpdate", BlindAssist.ScheduleOnUpdate);
end

function BlindAssist.Timer(iDelayTime, sText)
	BlindAssist.ChatPrint("Timer activated for "..iDelayTime.." seconds.");
	BlindAssist.Schedule(nil, iDelayTime, false, BlindAssist.QueueComm, sText);
end

function BlindAssist.IsScheduled(sName)
	for index, event in pairs(BlindAssist.Data.ScheduleQueue) do
		if (event.Name == sName) then
			return true;
		end
	end
end

function BlindAssist.ScheduledTimeLeft(sName)
	for index, event in pairs(BlindAssist.Data.ScheduleQueue) do
		if (event.Name == sName) then
			local amount = event.Time - GetTime();
			if (amount < 0) then
				amount = 0;
			end
			return amount;
		end
	end
	return 0;
end

function BlindAssist.ClearQueue(bCombatOnly)
	if (bCombatOnly) then
		for i = #BlindAssist.Data.ScheduleQueue, 1, -1 do
			if (BlindAssist.Data.ScheduleQueue[i].CombatOnly == true) then
				BlindAssist.DebugPrint("Clearing queue");
				table.remove(BlindAssist.Data.ScheduleQueue, i);
			end
		end
	else
		BlindAssist.Data.ScheduleQueue = { };	
	end
end

function BlindAssist.ClearEvent(sName)
	for i = #BlindAssist.Data.ScheduleQueue, 1, -1 do
		if (BlindAssist.Data.ScheduleQueue[i].Name == sName) then
			BlindAssist.DebugPrint("Removing event "..tostring(sName));
			table.remove(BlindAssist.Data.ScheduleQueue, i);
		end
	end
end

function BlindAssist.ClearEventStartsWith(sName)
	for i = #BlindAssist.Data.ScheduleQueue, 1, -1 do
		if (BlindAssist.Data.ScheduleQueue[i].Name == sName) then
			BlindAssist.DebugPrint("Removing event "..tostring(sName));
			table.remove(BlindAssist.Data.ScheduleQueue, i);
		end
	end
end

function BlindAssist.ScheduleOnUpdate()
	local currentTime = GetTime();
	for index, event in pairs(BlindAssist.Data.ScheduleQueue) do
		if (event.Time <= currentTime) then
			BlindAssist.DebugPrint("Fire event "..tostring(event.Name));
			if (event.Script) then
				BlindAssist.DebugPrint("Execute event function "..tostring(event.Name));
				event.Script(unpack(event.Arguments, 1, event.n));
			end
			BlindAssist.ClearEvent(event.Name);
			BlindAssist.ScheduleOnUpdate();
			return;
		end
	end

	if (#BlindAssist.Data.ScheduleQueue <= 0) then
		BlindAssistScheduleFrame:SetScript("OnUpdate", nil);
	end	
end

function BlindAssist.Pack(...)
    return { n = select('#', ...), ... };
end
