//
// CBaseClassThread.cpp
//
// (c)Copyright 2004 Steven J. Eschweiler. All Rights Reserved.
//

// Loosly based on code from: http://www.flipcode.com/articles/article_multithreading.shtml
#include "CBaseClassThread.h"

#include <iostream>

CBaseClassThread::CBaseClassThread()
{
   m_dwThreadID = 0;
   m_hThread = NULL;
   m_bThreadStarted = false;

   // Create Unique Windows Callback MSG Code
   char szTmp[256];
   sprintf_s(szTmp,"{CBaseClassThread}%d%d%d%d%d%d",rand(),rand(),rand(),rand(),rand(),rand());
   m_nControlID = ::RegisterWindowMessage(szTmp);
}

CBaseClassThread::~CBaseClassThread()
{
   End();
}

static DWORD WINAPI CThreadProc( CBaseClassThread *pThis )
{
   return pThis->ThreadProc();
}

bool CBaseClassThread::Begin()
{
   // _MT is defined for Multithreading... DO NOT DISABLE THESE LINES
   // To get this to work, link with the Multithreaded libraries
#if defined( _WIN32 ) && defined( _MT )
   if (m_hThread)
      End();  // just to be safe.

   // Start the thread.
   m_hThread = CreateThread( NULL,
      0,
      (LPTHREAD_START_ROUTINE)CThreadProc,
      this,
      0,
      (LPDWORD)&m_dwThreadID );
   if ( m_hThread==NULL )
   {
      m_bThreadStarted = false;
      return false;
   }
   else
   {
      m_bThreadStarted = true;
      return true;
   }
#endif
   return false;
}

void CBaseClassThread::End()
{
   // _MT is defined for Multithreading... DO NOT DISABLE THESE LINES
   // To get this to work, link with the Multithreaded libraries
#if defined( _WIN32 ) && defined( _MT )
   if ( m_hThread!=NULL )
   {
      m_bThreadStarted = false;
      WaitForSingleObject( m_hThread, INFINITE );
      CloseHandle( m_hThread );
      m_hThread = NULL;
   }
#endif
}

bool CBaseClassThread::IsRunning()
{
   DWORD dwExitCode=0;
   BOOL rc;

   if (m_bThreadStarted==false)
      return false; // Thread was never even started

   if (m_hThread==NULL)
      return false; // This should never occur actually because m_bThreadStarted would equal false

   rc = GetExitCodeThread(m_hThread,&dwExitCode);
   if (rc)
   {
      if (dwExitCode==STILL_ACTIVE)
      {
         return true;
      }
   }

   return false;
}

bool CBaseClassThread::WaitForThreadToFinish()
{
   if (m_hThread!=NULL)
   {
      if (WaitForSingleObject(m_hThread,INFINITE)==WAIT_FAILED)
         return false;
   }

   return true;
}

/*
bool CBaseClassThread::GetExitCode(DWORD &dwExitCode)
{
dwExitCode=0;

if (m_bThreadStarted)
{
if (m_hThread != NULL)
{
BOOL rc = GetExitCodeThread( m_hThread, &dwExitCode );
if (rc)
{
if (dwExitCode!=STILL_ACTIVE)
return true; // thread has terminated
}
}
}

return false;
}
*/
DWORD CBaseClassThread::ThreadProc()
{
   return 0;
}