/*
 *  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 <windows.h>

namespace Psychlops {

namespace Prototype {


	void* threadIDPtr(char *t) { return t; }
	void* threadFuncPtr(char *t) { return (t+8); }
	unsigned long __stdcall 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)()) {
		CreateThread(NULL, 0, &beginThread, (void*)func, 0, (LPDWORD)threadIDPtr(memory));
	}

	void Thread::sleep(int microsec) {
		Sleep(microsec/1000);
	}
	void Thread::yield() {
		Sleep(0);
	}
	int thread_priority_[5] =  {
		THREAD_PRIORITY_HIGHEST,
		THREAD_PRIORITY_NORMAL,
		THREAD_PRIORITY_LOWEST,
		THREAD_PRIORITY_IDLE,
		THREAD_PRIORITY_IDLE
	};
	void Thread::priority( Priority priority ) {
		SetThreadPriority(GetCurrentThread(), thread_priority_[priority]);
	}
	Thread::Priority Thread::priority() {
		int priority = GetThreadPriority(GetCurrentThread());
		switch(priority) {
			case THREAD_PRIORITY_HIGHEST:
				return Thread::HIGH;
			case THREAD_PRIORITY_NORMAL:
				return Thread::NORMAL;
			case THREAD_PRIORITY_LOWEST:
				return Thread::LOW;
			default:
			case THREAD_PRIORITY_IDLE:
				return Thread::IDLE;
		}
	}

}

}

