/*

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 "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 Continous Hist";
const LPWSTR g_pDesc = L"Generates features vector of V/H/2xDiagonal count of continous areas";
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;
}

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 )
		{
			DWORD dwWidthReal = ((int)((bih->biWidth+3)/4))*4;
			DWORD dwWidth = bih->biWidth;
			DWORD dwHeight = bih->biHeight;
			
			BYTE *pPixelsSrc = (BYTE*)&((RGBQUAD*)&bih[1])[256];

			DWORD dwLenDbls = dwWidth + dwHeight + dwWidth + dwHeight; // bylo -1 pozor??
			DWORD dwTgtLen = dwLenDbls * sizeof(double) + 4;
			BYTE *pTgtData = (BYTE*)malloc(dwTgtLen);//new double[dwLenDbls];
			memcpy(pTgtData, "VCTd", 4);
			double *pPtr = (double*)&pTgtData[4];
			BOOL *pbPtr2 = (BOOL*)malloc(dwLenDbls * sizeof(BOOL));
			for ( DWORD i = 0; i < dwLenDbls; i++ )
				pbPtr2[i] = FALSE;
			for ( DWORD i = 0; i < dwLenDbls; i++ )
				pPtr[i] = 0;
			BOOL *pbXHist = pbPtr2;
			BOOL *pbYHist = &pbXHist[dwWidth];
			BOOL *pbDHist = &pbYHist[dwHeight];
			double *pXHist = pPtr;
			double *pYHist = &pXHist[dwWidth];
			double *pDHist = &pYHist[dwHeight];
			for ( DWORD y = 0; y < dwHeight; y++ )
			{
				for ( DWORD x = 0; x < dwWidth; x++ )
				{
					if ( pPixelsSrc[y * dwWidthReal + x] )
					{
						if ( !pbXHist[x] )
						{
							pXHist[x]++;
							pbXHist[x] = TRUE;
						}
						if ( !pbYHist[y] )
						{
							pYHist[y]++;
							pbYHist[y] = TRUE;
						}
						if ( pbDHist[dwHeight + x - y] )
						{
							pDHist[dwHeight + x - y]++;
							pbDHist[dwHeight + x - y] = TRUE;
						}
					}
					else
					{
						if ( pbXHist[x] )
							pbXHist[x] = FALSE;
						if ( pbYHist[y] )
							pbYHist[y] = FALSE;
						if ( pbDHist[dwHeight + x - y] )
							pbDHist[dwHeight + x - y] = FALSE;
					}
				}
			}
			free(pbPtr2);
			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;
	}
}