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

#include <w_app.hpp>
#include <z_timer.hpp>

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

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

	case D_INITIALIZE:
		if (!timerID)
			timerID = SetTimer(NULL, ZAF_DEVICE_TIMER_ID, (UINT)interval, NULL);
		break;

	case D_OFF:
		deviceState = D_OFF;
		// Continue.

	case D_DEINITIALIZE:
		if (timerID)
			KillTimer(NULL, timerID);
		timerID = 0;
		break;

	case D_STATE:
		ccode = DeviceState();
		break;

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

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

	default:
		ccode = S_UNKNOWN;
		break;
	}

	// Return the control code.
	return (ccode);
}

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

	// Get the next event (without removing it from the queue).
	ZafEventStruct event;
	eventManager->Get(event, Q_NO_BLOCK | Q_BEGIN | Q_NO_DESTROY | Q_NO_POLL);

	if (event.osEvent.message == WM_TIMER && event.osEvent.wParam == timerID)
	{
		// Remove the event from the queue.
		eventManager->Get(event, Q_NO_BLOCK | Q_BEGIN | Q_NO_POLL);

		// Call the specified notification objects.
		ZafEventStruct timerEvent;
		timerEvent.device = this;
		for (ZafNotifyList::ZafNotifyElement *element = notifyList.First(); element; element = element->Next())
		{
			timerEvent.type = element->notifyMessage ? element->notifyMessage : notifyMessage;
			if (QueueEvents())
			{
				timerEvent.route = element->notifyObject;
				eventManager->Put(timerEvent);
			}
			else
				element->notifyObject->Event(timerEvent);
		}

		// Check for queued events.
		if (QueueEvents() && !notifyList.First())
		{
			timerEvent.type = notifyMessage;
			eventManager->Put(timerEvent);
		}
	}
}

unsigned long ZafTimer::SetInterval(unsigned long setInterval)
{
	interval = setInterval;

	if (timerID)
	{
		KillTimer(NULL, timerID);
		timerID = SetTimer(NULL, ZAF_DEVICE_TIMER_ID, (UINT)interval, NULL);
	}

	return (interval);
}


