#include "StdAfx.h"
#include "MainProcess.h"
#include "WinService.h"

CMainProcess::CMainProcess(void)
{
	m_hBackupDatabase = NULL;
	m_hCheckServices = NULL;
	m_hEvent1 = NULL;
	m_hEvent2 = NULL;
}

CMainProcess::~CMainProcess(void)
{
}

void CMainProcess::StartWork()
{
	m_hEvent1 = CreateEvent(NULL, TRUE, FALSE, NULL);
	if ( m_hEvent1 == NULL )
	{
		//_tprintf_s(_T("创建事件失败\n"));
		return;
	}

	m_hEvent2 = CreateEvent(NULL, TRUE, FALSE, NULL);
	if ( m_hEvent2 == NULL )
	{
		//_tprintf_s(_T("创建事件失败2\n"));
		return;
	}

	m_hCheckServices = CreateThread(NULL, 0, CheckSvcStatusThread, this, 0, NULL);
	if ( m_hCheckServices == NULL)
	{
		SetEvent(m_hEvent1);
		SetEvent(m_hEvent2);
		CloseHandle(m_hEvent1);
		CloseHandle(m_hEvent2);
		m_hEvent1 = NULL;
		m_hEvent2 = NULL;
		//_tprintf_s(_T("创建线程失败\n"));
		return;
	}

	m_hBackupDatabase = CreateThread(NULL, 0, BackupDatabaseThread, this, 0, NULL);
	if ( m_hBackupDatabase == NULL )
	{
		SetEvent(m_hEvent1);
		SetEvent(m_hEvent2);
		CloseHandle(m_hEvent1);
		CloseHandle(m_hEvent2);
		m_hEvent1 = NULL;
		m_hEvent2 = NULL;
		WaitForSingleObject(m_hCheckServices,INFINITE);
		if (m_hBackupDatabase)
			CloseHandle(m_hBackupDatabase);
		m_hBackupDatabase = NULL;
		//_tprintf_s(_T("创建线程失败2\n"));
		return;
	}
}

void CMainProcess::EndofWork()
{
	if ( m_hEvent1 )
	{
		SetEvent(m_hEvent1);
		CloseHandle(m_hEvent1);
	}

	if ( m_hEvent2 )
	{
		SetEvent(m_hEvent2);
		CloseHandle(m_hEvent2);
	}


	if ( m_hCheckServices )
	{
		WaitForSingleObject(m_hCheckServices,INFINITE);
		CloseHandle(m_hCheckServices);
	}

	if ( m_hBackupDatabase )
	{
		WaitForSingleObject(m_hBackupDatabase,INFINITE);
		CloseHandle(m_hBackupDatabase);
	}
}

DWORD CMainProcess::CheckSvcStatusThread(LPVOID lpVoid)
{
	CMainProcess *pthis = (CMainProcess*)lpVoid;

	do 
	{
	} while ( WaitForSingleObject(pthis->m_hEvent1, 200) == WAIT_TIMEOUT );

	return 0;
}

DWORD CMainProcess::BackupDatabaseThread(LPVOID lpVoid)
{
	CMainProcess *pthis = (CMainProcess*)lpVoid;

	do 
	{
	} while ( WaitForSingleObject(pthis->m_hEvent2, 200) == WAIT_TIMEOUT );

	return 0;
}