/*
 *  psychlops_app_init_Win32.h
 *  Psychlops Standard Library (Universal)
 *
 *  Last Modified 2005/12/19 by Kenchi HOSOKAWA
 *  (C) 2005 Kenchi HOSOKAWA, Kazushi MARUYA, Takao SATO
 */

#include "../../core/ApplicationInterfaces/psychlops_app_thread.h"
#include <ApplicationServices/ApplicationServices.h>
#include <CoreServices/CoreServices.h>

namespace Psychlops {

namespace Prototype {


	void* threadIDPtr(char *t) { return t; }
	void* threadFuncPtr(char *t) { return (t+8); }
	OSStatus beginThread(void *param) {
		void (*func)() = (void(*)())param;
		func();
		return 0;
	}

	Thread::Thread() {
		for(int i=0; i<32; i++) memory[i] = 0;
	}
	Thread::Thread(void (*func)()) {
		for(int i=0; i<32; i++) memory[i] = 0;
		create(func);
	}
	Thread::~Thread() {
		//TerminateThread(()threadIDPtr(memory))
	}
	void Thread::create(void (*func)()) {
		MPCreateTask((TaskProc)&beginThread, (void*)func, 4096, NULL, NULL, NULL, 0, (MPTaskID*)threadIDPtr(memory));
	}

	const unsigned int thread_state[5] = {
		kRunningThreadState,
		kRunningThreadState,
		kRunningThreadState,
		kReadyThreadState,
		kStoppedThreadState
	};
	void Thread::sleep(int microsec) {
		MPSemaphoreID delay;
		MPCreateSemaphore(0, 0, &delay);
		MPWaitOnSemaphore(delay, kDurationMicrosecond*microsec);
		MPDeleteSemaphore(delay);
	}
	void Thread::yield() {
		MPYield();
	}
	void Thread::priority( Priority priority ) {
		SetThreadState(kCurrentThreadID, thread_state[priority], kNoThreadID);
	}
	Thread::Priority Thread::priority() {
		ThreadState threadState;
		GetThreadState(kCurrentThreadID, &threadState);
		switch(threadState) {
			case kStoppedThreadState:
				return Thread::SLEEP;
			case kReadyThreadState:
				return Thread::IDLE;
			default:
			case kRunningThreadState:
				return Thread::NORMAL;
		}
	}
}

}

