/*

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 Plot";
const LPWSTR g_pDesc = L"Customizes plot's appearance";
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 strLegend;
	CString strXLabel;
	CString strYLabel;
	int nColor;
	int nMark;
	EnterCriticalSection(&m_cs);
	strLegend = m_strLegend;
//	strXLabel = m_strXLabel;
//	strYLabel = m_strYLabel;
	nColor = m_nColor;
	nMark = m_nMark;
	LeaveCriticalSection(&m_cs);

	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 )
			{
				ptrsrc = (BYTE*)&ph[1];
				DWORD dwLen = ph->dwDataLen * g_itemLen[ph->itemType];
				switch ( ph->dataType )
				{
				case DATATYPE_XVALUES:
					ar.Write(ph, sizeof(PLOTHEADER));
					ar.Write(ptrsrc, dwLen);
					ptrsrc += dwLen;
					break;
				case DATATYPE_YVALUES:
					ar.Write(ph, sizeof(PLOTHEADER));
					ar.Write(ptrsrc, dwLen);
					ptrsrc += dwLen;
					break;
				default:
					ptrsrc += dwLen;
					break;
				}
				ph = (PLOTHEADER*)ptrsrc;
			}
			PLOTHEADER phadd;
			phadd.dataType = DATATYPE_LEGEND;
			phadd.itemType = ITEMTYPE_WORD;
			phadd.dwDataLen = strLegend.GetLength();
			ar.Write(&phadd, sizeof(PLOTHEADER));
			ar.Write(strLegend, phadd.dwDataLen * sizeof(WORD));

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

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

			COLORREF cr;
			switch ( nColor )
			{
			case 0: // WHITE
				cr = RGB(0xff, 0xff, 0xff);
				break;
			case 1: // GREY
				cr = RGB(0x80, 0x80, 0x80);
				break;
			case 2: // RED
				cr = RGB(0xff, 0x00, 0x00);
				break;
			case 3: // GREEN
				cr = RGB(0x00, 0xff, 0x00);
				break;
			case 4: // BLUE
				cr = RGB(0x00, 0x00, 0xff);
				break;
			case 5: // YELLOW
				cr = RGB(0xff, 0xff, 0x00);
				break;
			case 6: // CYAN
				cr = RGB(0x00, 0xff, 0xff);
				break;
			case 7: // MAGENTA
				cr = RGB(0xff, 0x00, 0xff);
				break;
			default: // Unknown
				cr = RGB(0x40, 0x40, 0x40);
				break;
			}
			phadd.dataType = DATATYPE_COLOR;
			phadd.itemType = ITEMTYPE_DWORD;
			phadd.dwDataLen = 1;
			ar.Write(&phadd, sizeof(PLOTHEADER));
			ar.Write(&cr, sizeof(DWORD));

			BYTE cmark;

			switch ( nMark )
			{
			case 0:
				cmark = '.';
				break;
			case 1:
				cmark = 'x';
				break;
			case 2:
				cmark = '+';
				break;
			case 3:
				cmark = 'o';
				break;
			case 4:
				cmark = '-';
				break;
			default:
				cmark = 0;
				break;
			}
			phadd.dataType = DATATYPE_MARK;
			phadd.itemType = ITEMTYPE_BYTE;
			phadd.dwDataLen = 1;
			ar.Write(&phadd, sizeof(PLOTHEADER));
			ar.Write(&cmark, sizeof(BYTE));

			// zkopirujeme a ulozime data do fronty

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

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

			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++;
			pfh = (PLOTFILEHEADER*)(ptrsrc + sizeof(PLOTFILEHEADER));
		}
	}

	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_strLegend << m_nColor << m_nMark;
	}
	else
	{
		ar >> m_strLegend >> m_nColor >> m_nMark;
	}
}