/*

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 "..\\global\\headers.h"
#include <deque>

// jmeno, popis a cesta k bloku
const LPWSTR g_pName = L"Edit Global Plot";
const LPWSTR g_pDesc = L"Customizes plot's global data";
const LPWSTR g_pPath = L"Viewer tools";
// 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"PLOT IN"};
const WCHAR *g_pOutputNameArray[] = {L"PLOT OUT"};

// 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

//	m_nMark = 0;
//	m_nColor = 0;
//	m_strLegend = L"Unknown";
//	m_strXLabel = L"Item []";
//	m_strYLabel = L"Value []";
}
// destruktor
CImpBlock::~CImpBlock()
{
	if ( m_pxAutoTrigger )
		delete ( m_pxAutoTrigger );
	if ( m_pxConfig )
		delete ( m_pxConfig );
}

///////////////////////////////
// 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)
{

	CString strGraphName;
	CString strXLabel;
	CString strYLabel;
	BOOL bXRange;
	BOOL bYRange;
	double dMinX, dMaxX, dMinY, dMaxY;

	EnterCriticalSection(&m_cs);
	strGraphName = m_strGraphName;
	strXLabel = m_strXLabel;
	strYLabel = m_strYLabel;
	bXRange = m_bXRange;
	bYRange = m_bYRange;
	dMinX = m_dMinX;
	dMaxX = m_dMaxX;
	dMinY = m_dMinY;
	dMaxY = m_dMaxY;
	LeaveCriticalSection(&m_cs);

	PLOTHEADER phEnd;
	phEnd.dataType = DATATYPE_EOP;
	phEnd.dwDataLen = 0;
	phEnd.itemType = ITEMTYPE_BYTE;

	PLOTFILEHEADER pfhEnd;
	ZeroMemory(&pfhEnd, sizeof(pfhEnd));

	DWORD dwLayers = 0;
	std::deque<std::pair<LPVOID, DWORD> > dqData;

	for ( DWORD dwLayer = 0; dwLayer < pInputData->dwLayersArray[0]; dwLayer++ )
	{
		BYTE *ptrsrc = (BYTE*)pInputData->pDataArrayArray[0][dwLayer];
		PLOTFILEHEADER* pfh = (PLOTFILEHEADER*)ptrsrc;
		CMemFile mf;
		CArchive ar(&mf, CArchive::store);
		while ( memcmp(pfh->type, "plot", 4) == 0 )
		{	// jedna se o plot file
			ar.Write("plot", 4);
			ptrsrc = (BYTE*)&pfh[1];
			PLOTHEADER *ph = (PLOTHEADER*)ptrsrc;
			while ( ph->dataType != DATATYPE_EOP )
			{	 // prekopirovani vsech dat z plot souboru
				ptrsrc = (BYTE*)&ph[1];
				DWORD dwLen = ph->dwDataLen * g_itemLen[ph->itemType];
				ar.Write(ph, sizeof(PLOTHEADER));
				ar.Write(ptrsrc, dwLen);
				ptrsrc += dwLen;
				ph = (PLOTHEADER*)ptrsrc;
			}
			pfh = (PLOTFILEHEADER*)(ptrsrc + sizeof(PLOTHEADER));
			ar.Write(&phEnd, sizeof(phEnd));
		}

		

		// nyni pridame global zahlavi
		ar.Write("glbl", 4);
		PLOTHEADER pheader;

		// hlavicka dat GraphName

		pheader.dataType = DATATYPE_GRAPHNAME;
		pheader.dwDataLen = strGraphName.GetLength();
		pheader.itemType = ITEMTYPE_WORD;
		ar.Write(&pheader, sizeof(PLOTHEADER));
		ar.Write(strGraphName, pheader.dwDataLen * sizeof(WORD));

		// hlavicka dat XLabel

		pheader.dataType = DATATYPE_XLABEL;
		pheader.dwDataLen = strXLabel.GetLength();
		pheader.itemType = ITEMTYPE_WORD;
		ar.Write(&pheader, sizeof(PLOTHEADER));
		ar.Write(strXLabel, pheader.dwDataLen * sizeof(WORD));

		// hlavicka dat YLabel

		pheader.dataType = DATATYPE_YLABEL;
		pheader.dwDataLen = strYLabel.GetLength();
		pheader.itemType = ITEMTYPE_WORD;
		ar.Write(&pheader, sizeof(PLOTHEADER));
		ar.Write(strYLabel, pheader.dwDataLen * sizeof(WORD));

		if ( bXRange )
		{
			// hlavicka dat XRange

			pheader.dataType = DATATYPE_XRANGE;
			pheader.dwDataLen = 2;
			pheader.itemType = ITEMTYPE_DOUBLE;
			ar.Write(&pheader, sizeof(PLOTHEADER));
			ar.Write(&dMinX, sizeof(DOUBLE));
			ar.Write(&dMaxX, sizeof(DOUBLE));
		}

		if ( bYRange )
		{
			// hlavicka dat YRange

			pheader.dataType = DATATYPE_YRANGE;
			pheader.dwDataLen = 2;
			pheader.itemType = ITEMTYPE_DOUBLE;
			ar.Write(&pheader, sizeof(PLOTHEADER));
			ar.Write(&dMinY, sizeof(DOUBLE));
			ar.Write(&dMaxY, sizeof(DOUBLE));
		}

		// zkopirujeme a ulozime data do fronty



		ar.Write(&phEnd, sizeof(phEnd));
		ar.Write(&pfhEnd, sizeof(&pfhEnd));

		ar.Flush();
		mf.Flush();
		DWORD dwLen = (LONG)mf.GetLength();
		LPVOID data = malloc(dwLen);
		ar.Close();
		mf.SeekToBegin();
		mf.Read(data, dwLen);
		dqData.push_back(std::pair<LPVOID, DWORD>(data, dwLen));
		dwLayers++;
	}

	LockBlockData();
	DeleteBlockData();
	PrepareBlockData();
	NewBlockPortData(0, dwLayers);
	DWORD dwLayer = 0;
	while ( !dqData.empty() )
	{
		SetDataPtr(0, dwLayer, dqData.front().first, dqData.front().second);
		dqData.pop_front();
		dwLayer++;
	}
	UnlockBlockData();

	return S_OK;
}

STDMETHODIMP_(void) CImpBlock::Serialize(CArchive &ar)
{
	if ( ar.IsStoring() )
	{
		ar << m_strGraphName << m_strXLabel << m_strYLabel << m_bXRange << m_dMinX << m_dMaxX << m_bYRange << m_dMinY << m_dMaxY;
	}
	else
	{
		ar >> m_strGraphName >> m_strXLabel >> m_strYLabel >> m_bXRange >> m_dMinX >> m_dMaxX >> m_bYRange >> m_dMinY >> m_dMaxY;
	}
}