/*

Na zacatku tohoto souboru je nastaveni chovani bloku. Pote jsou zde funkce
nezvytne k vytvoreni instance COMu, a funkce, ktera vraci ukazatele na
rozhrani bloku. Prozatim se predpokladaji pouze 2 pridavna rozhrani k tomuto
objektu. 

-- IBlockConfig --
je urcene ke konfiguraci bloku. Je pouzito
v pripade, kdyz uzivatel klikne pravym tlacitkem mysi na blok a vybere
volbu "properties...". Melo by se otevrit okno s nastavenim, ktere musi
byt implementovano

-- IBlockAutoTrigger --
slouzi k automatickemu spousteni procesu. Vyuzije se napriklad pri realtime
zpracovani zvuku a videa, kdy potrebujeme pravidelne zpracovavat useky dat

*/

#include "stdafx.h"
#include <math.h>
#include "imp_block.h"
//#include "imp_config.h"
//#include "imp_autotrigger.h"
#include <deque>

// jmeno, popis a cesta k bloku
const LPWSTR g_pName = L"Gen Circle Hist";
const LPWSTR g_pDesc = L"Generates features vector of circle pixel histogram";
const LPWSTR g_pPath = L"Feature Extraction";
// jestli ma blok rohrani, odkomentujte prislusny radek
//#define __BLOCKHAVECONFIGWINDOW
//#define __BLOCKHAVEAUTOTRIGGER
// pocty vstupnich a vystupnich portu
const DWORD g_dwInPortCount = 1;
const DWORD g_dwOutPortCount = 1;
// nazvy vstupnich a vystupnich portu
const WCHAR *g_pInputNameArray[] = {L"BBMP"};
const WCHAR *g_pOutputNameArray[] = {L"VECTOR"};

// Tyto funkce nemenit !!!
// funkce volana klientskym programem k vytvoreni instance tridy

HRESULT CreateBlockInstance(REFIID riid, void **ppv)
{
	return CImpBlock::CreateInstance(riid, ppv);
}
// staticka funkce, ktera vytvari instanci tridy
HRESULT CImpBlock::CreateInstance(const IID &riid, void **ppv)
{
	CImpBlock* pObj; 
	pObj = new CImpBlock();
	if (pObj == NULL) 
		return E_OUTOFMEMORY; 
	HRESULT hr; 
	if ( FAILED(hr = pObj->QueryInterface(riid, (void**)ppv))) 
		delete pObj ; 
	return hr; 
}
// funkce, ktera vraci adresu rozhrani
void* CImpBlock::GetInterface(REFIID riid)
{
#ifdef __BLOCKHAVECONFIGWINDOW
	if ( IID_IBlockConfig == riid )
		return m_pxConfig;
#endif
#ifdef __BLOCKHAVEAUTOTRIGGER
	if ( IID_IBlockAutoTrigger == riid )
		return m_pxAutoTrigger;
#endif
	return NULL;
}
// konstruktor
CImpBlock::CImpBlock() : m_pxConfig(NULL), m_pxAutoTrigger(NULL)
{
#ifdef __BLOCKHAVECONFIGWINDOW
	m_pxConfig = new CImpBlockConfig(this);
#endif
#ifdef __BLOCKHAVEAUTOTRIGGER
	m_pxAutoTrigger = new CImpBlockAutoTrigger(this);
#endif
	m_dwInPortCount = g_dwInPortCount;
	m_dwOutPortCount = g_dwOutPortCount;
	m_pName = g_pName;
	m_pDesc = g_pDesc;
	m_pPath = g_pPath;
	m_pInputNameArray = g_pInputNameArray;
	m_pOutputNameArray = g_pOutputNameArray;

	// inicializace promennych

}
// destruktor
CImpBlock::~CImpBlock()
{
#ifdef __BLOCKHAVEAUTOTRIGGER
	if ( m_pxAutoTrigger )
		delete ( m_pxAutoTrigger );
#endif
#ifdef __BLOCKHAVECONFIGWINDOW
	if ( m_pxConfig )
		delete ( m_pxConfig );
#endif
}

///////////////////////////////
// TYTO FUNKCE IMPLEMENTOVAT //
///////////////////////////////

STDMETHODIMP CImpBlock::InitInstance()
{
	CBlock::InitInstance();
	return S_OK;
}

STDMETHODIMP CImpBlock::ExitInstance()
{
	CBlock::ExitInstance();
	return S_OK;
}

STDMETHODIMP CImpBlock::ProcessRev(const DWORD dwProcessId, REVDATAMAP &rRevDataMap)
{
	return S_OK;
}

STDMETHODIMP CImpBlock::ClearRevMap(REVDATAMAP &rRevDataMapClean)
{
	return S_OK;
}

inline int GetPixelCount(BYTE* pData, int nWidth, int nHeight, int x0, int y0, int x, int y)
{
	int ret = 0;
	int nWidthReal = ((int)((nWidth + 3)/4))*4;

	if (	x0 + x < nWidth && 
			x0 + x >= 0 &&
			y0 + y < nHeight &&
			y0 + y >= 0 && 
			pData[(x0+x) + nWidthReal * (y0+y)] )
			ret++;

	if (	x0 - x < nWidth && 
			x0 - x >= 0 &&
			y0 + y < nHeight &&
			y0 + y >= 0 &&
			pData[(x0-x) + nWidthReal * (y0+y)] )
			ret++;

	if (	x0 + x < nWidth && 
			x0 + x >= 0 &&
			y0 - y < nHeight &&
			y0 - y >= 0 &&
			pData[(x0+x) + nWidthReal * (y0-y)] )
			ret++;

	if (	x0 - x< nWidth && 
			x0 - x >= 0 &&
			y0 + y < nHeight &&
			y0 + y >= 0 &&
			pData[(x0-x) + nWidthReal * (y0+y)] )
			ret++;

	if (	x0 + y < nWidth && 
			x0 + y >= 0 &&
			y0 + x < nHeight &&
			y0 + x >= 0 && 
			pData[(x0+y) + nWidthReal * (y0+x)] )
			ret++;

	if (	x0 - y < nWidth && 
			x0 - y >= 0 &&
			y0 + x < nHeight &&
			y0 + x >= 0 &&
			pData[(x0-y) + nWidthReal * (y0+x)] )
			ret++;

	if (	x0 + y < nWidth && 
			x0 + y >= 0 &&
			y0 - x < nHeight &&
			y0 - x >= 0 &&
			pData[(x0+y) + nWidthReal * (y0-x)] )
			ret++;

	if (	x0 - y < nWidth && 
			x0 - y >= 0 &&
			y0 + x < nHeight &&
			y0 + x >= 0 &&
			pData[(x0-y) + nWidthReal * (y0+x)] )
			ret++;
	
	return ret;
}

STDMETHODIMP CImpBlock::ProcessData(const LPBLOCKDATA pInputData)
{
	BOOL bRet = TRUE;
	std::deque<std::pair<void*, DWORD> > dqLayers;
	
	DWORD dwLayers = pInputData->dwLayersArray[0];
	DWORD dwUsedLayers = 0;

	for ( DWORD dwLayer = 0; dwLayer < dwLayers; dwLayer++ )
	{
		BYTE *pDataSrc = (BYTE*)pInputData->pDataArrayArray[0][dwLayer];
		BITMAPFILEHEADER *bfh = (BITMAPFILEHEADER*)pDataSrc;
		BITMAPINFOHEADER *bih = (BITMAPINFOHEADER*)&bfh[1];
		DWORD dwSrcLen = pInputData->dwDataLenArrayArray[0][dwLayer];
		if ( dwSrcLen > sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) &&
			bfh->bfType == 0x4D42 && 
			bfh->bfSize == dwSrcLen &&
			bih->biBitCount == 8 &&
			bih->biCompression == 0 &&
			bih->biPlanes == 1 )
		{
			int nWidthReal = ((int)((bih->biWidth+3)/4))*4;
			int nWidth = bih->biWidth;
			int nHeight = bih->biHeight;
			
			int x0 = nWidth/2;
			int y0 = nHeight/2;

			BYTE *pPixelsSrc = (BYTE*)&((RGBQUAD*)&bih[1])[256];

			int radius = 1;
			int maxradius = (int)sqrt(((nWidth*nWidth) + (nHeight*nHeight))/4.0);

			DWORD dwTgtLen = (maxradius - radius) * sizeof(double) + 4;
			BYTE* pTgtData = (BYTE*)malloc(dwTgtLen);
			memcpy(pTgtData, "VCTd", 4);
			double* pPtr = (double*)&pTgtData[4];
			double dMax = 0;
			for ( int i = 0; i < maxradius - 1; i++ )
				pPtr[i] = 0;
			while ( radius < maxradius )
			{
				int f = 1-radius;
				int ddF_x = 1;
				int ddF_y = -2 * radius;
				int x = 0;
				int y = radius;
				pPtr[radius-1] += GetPixelCount(pPixelsSrc, nWidth, nHeight, x0, y0, 0, radius)/2;

				while ( x < y )
				{
					ASSERT(ddF_x == 2*x+1);
					ASSERT(ddF_y == -2*y);
					ASSERT(f == x*x + y*y - radius*radius + 2*x - y + 1);
					if ( f >= 0 )
					{
						y--;
						ddF_y += 2;
						f += ddF_y;
					}
					x++;
					ddF_x += 2;
					f += ddF_x;
					pPtr[radius-1] += GetPixelCount(pPixelsSrc, nWidth, nHeight, x0, y0, x, y);
				}
				if ( pPtr[radius-1] > dMax )
					dMax = pPtr[radius-1];
				radius++;
			}

			//normalizace
			for ( DWORD i = 0; i < maxradius - 1; i++ )
				pPtr[i] /= dMax;

			dqLayers.push_back(std::pair<LPVOID, DWORD>(pTgtData, dwTgtLen));
			dwUsedLayers++;
		}
	}

	LockBlockData();
	DeleteBlockData();
	PrepareBlockData();
	NewBlockPortData(0, dwUsedLayers);
	dwUsedLayers = 0;
	while ( !dqLayers.empty() )
	{
		SetDataPtr(0, dwUsedLayers++, (*dqLayers.begin()).first, (*dqLayers.begin()).second);
		dqLayers.pop_front();
		
	}
	UnlockBlockData();

	return bRet ? S_OK : S_FALSE;
}

STDMETHODIMP_(void) CImpBlock::Serialize(CArchive &ar)
{
	if ( ar.IsStoring() )
	{
		ar;
	}
	else
	{
		ar;
	}
}