#include "ImagerHandler.h"

PIseries::ImagerHandler::ImagerHandler(evo::IRImager* irImager)
{
	_rawDataBuffer = 0;
	_isIrImagerSet = false;
	_isInit = false;
	_irImager = NULL;
	_hData = NULL;
	if (irImager)
	{
		if (_setirImager(&irImager)) _isIrImagerSet = true;
	}
}

bool PIseries::ImagerHandler::LoadDataHandler(unsigned short** data)
{
	if (!_isValid(data)) return false;
	if (!_isIrImagerSet) return false;

	_hData = data;

	if (*_hData = new unsigned short[_rawDataBuffer])
	{
		_isInit = true;
		return true;
	}
	else return false;
}

void PIseries::ImagerHandler::onThermalFrame(unsigned short* data, unsigned int w, unsigned int h, evo::IRFrameMetadata meta, void* arg)
{
	if (!_isInit) return;

	if (_isValid(data))
	{
		try
		{
			unsigned int buff = w * h * sizeof(*data);
			memcpy_s(*_hData, _rawDataBuffer, data, buff);
		}
		catch (std::bad_exception& e)
		{
			LPCSTR str = e.what();
			MessageBox(NULL, str, TEXT("Warning"), MB_OK);
		}
	}
}

void PIseries::ImagerHandler::onRawFrame(unsigned char* data, int size)
{
	//if (!_isValid<unsigned char>(data)) throw thermoCamera::MyError::dataIsNotValid;

	_irImager->process(data);
	
}

void PIseries::ImagerHandler::setIRImager(evo::IRImager* irImager)
{
	if (irImager)
	{
		if (_setirImager(&irImager)) _isIrImagerSet = true;
	}
}

template <typename T>
BOOL PIseries::ImagerHandler::_isValid(T* data)
{
	return (data) ? true : false;
}

BOOL PIseries::ImagerHandler::_setirImager(evo::IRImager** irImager)
{
	_irImager = *irImager;
	_irImager->setClient(this);
	_rawDataBuffer = _irImager->getRawBufferSize();
	return (_rawDataBuffer > 0) ? true : false;
}