#include "stdafx.h"
#include "imp_autotrigger.h"
#include "imp_block.h"
#include <math.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;
	m_pThread->SetThreadPriority(THREAD_PRIORITY_HIGHEST);
	return S_OK;
}

STDMETHODIMP CImpBlockAutoTrigger::Stop()
{
	if ( m_pThread )
	{
		SetEvent(((CImpBlock*)m_pUnkOuter)->m_hEventQuit);
		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_()
{
	CImpBlock* pThis = (CImpBlock*)m_pUnkOuter;
	// pThis->m_hEventQuit - událost, signalizující nutnost ukončení vlákna


	// nakonec resetujeme udalost ukonceni
	ResetEvent(pThis->m_hEventQuit);
	return 0;
}