/***************************************************************************
                             Thread.cpp
                             -------------------
    Begin                : Sat Oct 26, 2001
    Objective            : Wrapper class for a thread
    Author               : Drew Hall
    Email                : dhall@Zero-Soft.com
 ***************************************************************************/

#include "stdafx.h"

CThread::CThread() : m_hThread(NULL), m_dwThreadID(0), m_bIsRunning(false), m_lpParam(NULL)
{
   m_hThread = CreateThread(NULL, 0, BounceFunc, this, CREATE_SUSPENDED, &m_dwThreadID);
   if(!m_hThread)
      throw(CException(23, "Could not create thread!", __LINE__, __FILE__));
}

CThread::CThread(bool bStarted, int nPriority) : m_bIsRunning(bStarted), m_hThread(NULL), m_dwThreadID(0), m_lpParam(lpParam)
{
   m_hThread = CreateThread(NULL, 0, BounceFunc, this, bStarted, &m_dwThreadID);
   if(!m_hThread)
      throw(CException(23, "Could not create thread!", __LINE__, __FILE__));

   if(!::SetThreadPriority(m_hThread, nPriority))
      throw(CException(24, "Could not set thread priority!", __LINE__, __FILE__));
}

int CThread::GetPriority()
{
   return ::GetThreadPriority(m_hThread);
}

bool CThread::SetPriority(int nPriority)
{
   return ::SetThreadPriority(m_hThread);
}

bool CThread::Start()
{
   if(m_bIsRunning == true)
      return true;
  
   if(ResumeThread(m_hThread) == 0xFFFFFFFF)
      return false;

   m_bIsRunning = true;
   return true;

}

bool CThread::Stop()
{
   if(m_bIsRunning == false)
      return true;

   if(SuspendThread(m_hThread) == 0xFFFFFFFF)
      return false;

   m_bIsRunning = false;
   return true;
}

bool CThread::IsRunning()
{
   return m_bIsRunning;
}

bool CThread::GetThreadInfo(LPFILETIME lpCreateTime, LPFILETIME lpExitTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime)
{
   return ::GetThreadTimes(m_hThread, lpCreateTime, lpExitTime, lpKernelTime, lpUserTime);
}

void Delay(unsigned long nSec)
{
   unsigned long timer;

   timer = GetTickCount() + (nSec * 1000);
   while(GetTickCount() < timer && m_bIsRunning)
   {
      Sleep(1000);
      Sleep(0);
   }
}

DWORD WINAPI BounceFunc(LPVOID pPtr)
{
   ((CThread*)pPtr)->Execute(NULL);
   return 0;
}

