//	Zinc Application Framework - D_TIMER.CPP
//	COPYRIGHT (C) 1990-1999.  All Rights Reserved.
//	Zinc Software Incorporated.  Pleasant Grove, Utah  USA

#include <time.h>
#include <z_timer.hpp>

// ----- ZafTimer ----------------------------------------------------------

ZafEventType ZafTimer::Event(const ZafEventStruct &event)
{
	ZafEventType ccode = event.type;
	switch (ccode)
	{
	case D_ON:
		{
			ZafDeviceState initialState = DeviceState();
			deviceState = ccode;

			// If didn't change states, don't reinitialize the timer.
			if (initialState == DeviceState())
				break;
		}
		// Continue.

	case D_INITIALIZE:
		lastTime = clock();
		break;

	case D_OFF:
		deviceState = ccode;
		break;

	case D_STATE:
		ccode = DeviceState();
		break;

	case S_ADD_OBJECT:
		notifyList.Add(event.windowObject);
		break;

	case S_SUBTRACT_OBJECT:
		notifyList.Subtract(event.windowObject);
		break;

	default:
		ccode = S_UNKNOWN;
		break;
	}

	return (ccode);
}

void ZafTimer::Poll(void)
{
	if (DeviceState() == D_OFF)
		return;

	unsigned long now = clock();

	if (interval == 0 || (now - lastTime) * 1000 / CLOCKS_PER_SEC >= interval)
	{
		lastTime = clock();

		ZafEventStruct timerEvent;
		timerEvent.device = this;

		// Notify objects with timer event.
		for (ZafTimer::ZafNotifyList::ZafNotifyElement *notifyElement = notifyList.First(); notifyElement;
			notifyElement = notifyElement->Next())
		{
			timerEvent.type = notifyElement->notifyMessage ? notifyElement->notifyMessage : notifyMessage;
			if (QueueEvents())
			{
				timerEvent.route = notifyElement->notifyObject;
				eventManager->Put(timerEvent);
			}
			else
				notifyElement->notifyObject->Event(timerEvent);
		}

		if (QueueEvents() && !notifyList.First())
		{
			timerEvent.type = notifyMessage;
			timerEvent.device = this;
			eventManager->Put(timerEvent);
		}
	}
}

unsigned long ZafTimer::SetInterval(unsigned long tInterval)
{
	interval = tInterval;
	return (interval);
}


