//---------------------------------------------------------------------------


#pragma hdrstop

#include "CameraReader.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)

bool TFiCamera::Done = false;


TFiCamera::TFiCamera(int ID, TExtendedSource *Source)
{
	FSource = Source;
	FId = ID;
	FFrameIndex = 0;
}

bool TFiCamera::Init()
{
	char str[128];

	return StatusOK;
}


TFiCamera::~TFiCamera()
{
	WaitForSingleObject(hProcessThread, 5000);
    CloseHandle(hProcessThread);
}


void TFiCamera::Start()
{
	SECURITY_ATTRIBUTES sa = {
		sizeof(SECURITY_ATTRIBUTES), /* structure size */
		0,      /* No security descriptor */
		true    /* Thread handle is inheritable */
	};
	hProcessThread = (HANDLE)_beginthreadex(&sa, 4096, ThreadFunction, (void*)this, 0, NULL);
}


unsigned int __stdcall TFiCamera::ThreadFunction(void *param)
{
	TFiCamera *camera = reinterpret_cast<TFiCamera*>(param);

	char path[128];

	if (camera->StatusOK)
	{
		while (!camera->Done)
		{
			sprintf(path, "Frame: %d-%06d.bmp", camera->FId, camera->FFrameIndex++);
//			MessageBox(NULL, path, "FrameIndex", MB_OK);
			Sleep(1);
		}
	}

	_endthread();
	return 0;
}


//---------------------------------------------------------------------------


TCameraReader::TCameraReader()
{
	FCameraCount = 0;
}


TCameraReader::~TCameraReader()
{
	for (vector<TFiCamera*>::iterator it = FCameras.begin(); it < FCameras.end(); it++)
	{
		if ((*it) != NULL)
		{
			delete (*it);
		}
	}
	FCameras.clear();
}


TFiCamera* TCameraReader::AddCamera(int ID, TExtendedSource *Source)
{
	TFiCamera *camera = new TFiCamera(ID, Source);
	if (camera != NULL)
	{
		FCameras.push_back(camera);
	}
	return camera;
}


void TCameraReader::Init(TExtendedSources &Sources)
{
	char str[128];

	FSources = Sources;

	TFiCamera *camera;

	for (int i = 0; i < FSources.size(); i++)
	{
		camera = AddCamera(i, FSources[i]);

		if (camera != NULL)
		{
			if (!camera->StatusOK)
			{
				sprintf(str, "Camera %d creating error", i);
				MessageBox(NULL, str, "Error", MB_OK);
			}

			camera->Init();
		}
	}
}


void TCameraReader::Run()
{
	for (vector<TFiCamera*>::iterator it = FCameras.begin(); it < FCameras.end(); it++)
	{
		(*it)->Start();
	}
}

