#include "stdafx.h"
#include "imp_autotrigger.h"
#include "imp_block.h"

CImpBlockAutoTrigger::CImpBlockAutoTrigger(IUnknown *pUnkOuter) : CBlockAutoTrigger(pUnkOuter)
{
	m_pThread = NULL;
}

CImpBlockAutoTrigger::~CImpBlockAutoTrigger()
{
	Stop();
}

STDMETHODIMP CImpBlockAutoTrigger::Start(TRIGGERPROC pTrigProc, HANDLE hBlock)
{
	m_hBlock = hBlock;
	m_pTrigProc = pTrigProc;
	m_pThread = AfxBeginThread(Process, this);
	m_pThread->m_bAutoDelete = FALSE;
	TRACE(L"Created thread %x\r\n", m_pThread);
	return S_OK;
}

STDMETHODIMP CImpBlockAutoTrigger::Stop()
{
	if ( m_pThread )
	{
		SetEvent(((CImpBlock*)m_pUnkOuter)->m_hEventQuit);
		TRACE(L"Destroying thread %x\r\n", m_pThread);
		
		WaitForSingleObject(m_pThread->m_hThread, INFINITE);
		delete(m_pThread);
		m_pThread = NULL;
	}
	return S_OK;
}

UINT CImpBlockAutoTrigger::Process(LPVOID p)
{
	return ((CImpBlockAutoTrigger*)p)->Process_();
}

UINT CImpBlockAutoTrigger::Process_()
{
	//TRACE(L"Started thread %x\r\n", m_pThread);
	CImpBlock* pThis = (CImpBlock*)m_pUnkOuter;
	HANDLE hEventArray[2];
	hEventArray[0] = pThis->m_hEvent;
	hEventArray[1] = pThis->m_hEventQuit;
	BOOL bRepeat = TRUE;
	DWORD retwfo;
	do
	{
		switch ( retwfo = WaitForMultipleObjects(2, hEventArray, FALSE, INFINITE) )
		{
		case WAIT_OBJECT_0:
			{
//				TRACE("x");
				m_pTrigProc(m_hBlock);
			}
			break;
		case WAIT_OBJECT_0+1:
			bRepeat = FALSE;
			break;
		default:
			MessageBox(NULL, L"Error?", L"Autotrigger at bloadcamera", MB_OK | MB_ICONERROR);
			break;
		}
	}while (bRepeat);
	ResetEvent(pThis->m_hEventQuit);
	//TRACE(L"Ending thread %x\r\n", m_pThread);
	return 0;
}