#include "YaRRincludes.h"

/************************************** Polite Request ***************************************
** I have put a lot of time and effort into YaRR. If you want to use some of the source     **
** please tell me. Anything used from YaRR must be open source, as is scripts.dll.          **
***************************************** Thank you *****************************************/

YaRRThink::ThinkEvent *YaRRThink::Events = 0;

void YaRRThink::Startup()
{
	DLOG;

}

void YaRRThink::DeleteLinkList(ThinkEvent *EventList)
{
	if(!EventList)
	{
		return;
	}
	DeleteLinkList(EventList->Next);
	Dealloc(ThinkEvent, EventList);
}

void YaRRThink::Shutdown()
{
	DLOG;
	if(Events)
	{
		DeleteLinkList(Events);
	}
	Events = 0;
}

void YaRRThink::Think()
{
	DLOG;
	ThinkEvent *Prev = 0;
	for(ThinkEvent *x = Events; x != 0;)
	{
		
		if(clock() - x->Clock_Start >= x->Timeout*CLOCKS_PER_SEC)
		{
			x->Callback(x->Data, x->Number);
			if(!Prev)
			{
				Events = x->Next;
				Dealloc(ThinkEvent, x);
				x = 0;
			}
			else
			{
				Prev->Next = x->Next;
				Dealloc(ThinkEvent, x);
				x = Prev;
			}

		}
		if(x)
		{
			x = x->Next;
		}
		
		Prev = x;
	}
}

void YaRRThink::Add_Timer(float Timeout_s, void (*Callback)(void *, int), void *Data, int Number)
{
	DLOG;
	ThinkEvent te;
	te.Number = Number;
	te.Data = Data;
	te.Timeout = Timeout_s;
	te.Clock_Start = clock();
	te.Callback = Callback;
	te.Next = 0;

	ThinkEvent *X = Events, *Y = 0;

	while(X != 0)
	{
		Y = X;
		X = X->Next;
		
	}
	if(Y == 0)
	{
		Events = Alloc(ThinkEvent);
		Y = Events;
	}
	else
	{
		Y->Next = Alloc(ThinkEvent);
		Y = Y->Next;
	}

	memcpy((void *)Y, &te, sizeof(ThinkEvent));
}