#include <LPeriodical.h>
#include "mac_cosmos.h"
#include "AppConstants.h"

extern "C" void wakeup_task(unsigned int key);

extern Point curMouse;

class CYieldRepeater : public LPeriodical
{
  public:
				static UInt32 curTick;
				CYieldRepeater(SInt32 quantum = -1) 
					: mQuantum(quantum), mNextTicks(0)
				{
					StartRepeating();
				}
	virtual void	SpendTime( const EventRecord& inMacEvent ) {

					if ( inMacEvent.what != 0 ) {
						theApp->SetSleepTime(0);
						return;
					}
					
					// set curMouse
					if ( inMacEvent.what != kHighLevelEvent )
						curMouse = inMacEvent.where;

					// wakeup event_thread if exsits
					extern LThread * event_thread;
					if ( event_thread ) {
						event_thread->Resume();
						LThread::Yield(event_thread);
					}
					
					// yield to the other threads
					if (mQuantum < 0)
					{
						LThread::Yield();
					}
					else
					{
						theApp->SetSleepTime(0);
						do
						{
							LThread::Yield();
							curTick = TickCount();
							// If controled cpu too long time,
							// forcely switched to main thread and come here
							if ( LThread::GetPrevThread() && 
								curTick - LThread::GetPrevThread()->mTick > thTicksHeavyAlert ) {
								printf("!!! Heavy Thread : %s(%.1fsec)\n", LThread::GetPrevThread()->mName, (float)(curTick - LThread::GetPrevThread()->mTick)/60.0);
							}
							if ( LThread::GetPrevThread() == LThread::GetMainThread() ) {
								theApp->SetSleepTime(1);
								break;
							}
						} while (curTick <= mNextTicks);
						mNextTicks = curTick + mQuantum;
					}
				}
  protected:
	SInt32			mQuantum;
	UInt32			mNextTicks;
	
	friend class LThread;
};