#include <xtl.h>
#include "Thread.h"

CThread::CThread(void)
{
	AttachFunc(CThread::Sample);
};

CThread::~CThread(void)
{
	//printf("Killing %s [%d]\r\n",m_sFuncName.c_str(),m_dThreadId);
	Stop();	
};

/**
Attache une function qui va etre executé
**/
void CThread::AttachFunc( LPTHREAD_START_ROUTINE lpThreadFunc )
{
	m_pThreadFunc=lpThreadFunc;
};
/**
Termine un thread
**/
HRESULT CThread::Stop()
{
	if(m_hThread)
	{
		//termine le thread
		//TerminateThread(m_hThread,(DWORD(-1)));
		//CloseHandle(m_hThread);
	}
	return S_OK;
}

/**
Lance le thread
**/
HRESULT CThread::RunThread()
{
	m_hThread = CreateThread( 
		NULL,                   // default security attributes
		0,                      // use default stack size  
		m_pThreadFunc,			// thread function name
		this,					// argument to thread function 
		CREATE_SUSPENDED,       // use default creation flags 
		&m_dThreadId			// returns the thread identifier 
	);   

	//printf("Starting: %s [%08x]\r\n", m_sFuncName.c_str(), m_dThreadId);
	if(m_hThread==NULL)
	{
		DebugBreak();
		return E_FAIL;
	}
	XSetThreadProcessor(m_hThread,2);
	SetThreadPriority(m_hThread,THREAD_PRIORITY_HIGHEST);
	ResumeThread(m_hThread);
	CloseHandle(m_hThread);
	return S_OK;
}

/**
Sample
**/
DWORD WINAPI CThread::Sample(void * Obj)
{
	CThread * _this=(CThread*)Obj;

	//printf("Sample\r\n");
	Sleep(500);

	return 0;
}

//STILL_ACTIVE if still running
DWORD CThread::getExitCode()
{
	DWORD ExitCode;
	GetExitCodeThread(m_hThread,&ExitCode);
	return ExitCode;
}
