// ProcessThread.cpp : implementation file
//

#include "stdafx.h"
#include "xpeluc01.h"
#include "ProcessThread.h"
#include "SchemeDoc.h"
#include "BlockItem.h"
#include "SchemeView.h"


// CProcessThread

//IMPLEMENT_DYNCREATE(CProcessThread, CWinThread)

CProcessThread::CProcessThread(CSchemeDoc* ptr)
{
	m_pDocument = ptr;
	m_pThread = NULL;
}

CProcessThread::~CProcessThread()
{
}

BOOL CProcessThread::Release()
{
	delete(this);
	return TRUE;
}

UINT CProcessThread::ThreadProcRun(LPVOID pParam)
{
    CProcessThread* pObject = (CProcessThread*)pParam;
	UINT ret = pObject->ThreadProc();
	pObject->m_pThread = NULL;
	return ret;
}

BOOL CProcessThread::Run(BOOL bCreateNewThread)
{
	if ( bCreateNewThread )
	{
		if ( m_pThread )
			return FALSE;
		m_pThread = AfxBeginThread(ThreadProcRun, this);
	}
	else
		ThreadProcRun(this);
	return TRUE;
}

BOOL CProcessThread::IsRunning()
{
	return (m_pThread != NULL);
}

// CProcessThread message handlers

UINT CProcessThread::ThreadProc()
{
	if ( !m_pDocument )
		return -1;
	std::set<CBlockItem*>::iterator it;
	it = m_pDocument->m_setRun.begin();

	LARGE_INTEGER liF, liTStart, liTEnd;
	QueryPerformanceFrequency(&liF);
	QueryPerformanceCounter(&liTStart);

	while ( it != m_pDocument->m_setRun.end() )
	{
		REVDATAMAP r;
		(*it)->Process(m_pDocument->m_dwLastProcessId, r);
		r.clear();
		it++;
	}
	m_pDocument->m_dwLastProcessId++;
/*
	POSITION pos = m_pDocument->GetFirstViewPosition();
	while ( pos )
	{
		CView *pView = m_pDocument->GetNextView(pos);
		pView->PostMessage(WM_UPDATEVIEW);
	}
*/
	QueryPerformanceCounter(&liTEnd);
	double dLastProcessTime = ( (double)(liTEnd.QuadPart - liTStart.QuadPart) / liF.QuadPart * 1000.0 );

	TRACE("Process no: %d, time: %fms\r\n", m_pDocument->m_dwLastProcessId, dLastProcessTime);

	return 0;
}