/*

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"Load file";
const LPWSTR g_pDesc = L"Loads one or multiple files";
const LPWSTR g_pPath = L"General";
// jestli ma blok rohrani, odkomentujte prislusny radek
#define __BLOCKHAVECONFIGWINDOW
//#define __BLOCKHAVEAUTOTRIGGER
// pocty vstupnich a vystupnich portu
const DWORD g_dwInPortCount = 2;
const DWORD g_dwOutPortCount = 1;
// nazvy vstupnich a vystupnich portu
const WCHAR *g_pInputNameArray[] = {L".RAW/NAME", L".RAW/DWid"};
const WCHAR *g_pOutputNameArray[] = {L"FILE"};

// 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_bCheckFile = FALSE;
	m_bDisableInput = FALSE;
	m_bSkipEmptyLayers = FALSE;
}
// 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 strName;
	BOOL bCheckFile;
	BOOL bDisableInput;
	BOOL bSkipEmptyLayers;
	std::deque<std::pair<void*, DWORD> > dqLayers;

	DWORD dwLayers = 0;

	BOOL bExtId = FALSE;
	BOOL bLayerRqst = FALSE;
	DWORD dwId = 0;

	// vytvoreni kopie parametru

	EnterCriticalSection(&m_cs);
	strName = m_strName;
	bCheckFile = m_bCheckFile;
	bDisableInput = m_bDisableInput;
	bSkipEmptyLayers = m_bSkipEmptyLayers;
	LeaveCriticalSection(&m_cs);

	// zpracovani dat

	// v pripade, ze je zapojena promenna ID, pouzit ji

	if ( pInputData->dwLayersArray[1] == 1 &&
		pInputData->dwDataLenArrayArray[1][0] == sizeof(DWORD) )
	{
		bExtId = TRUE;
		memcpy(&dwId, pInputData->pDataArrayArray[1][0], sizeof(DWORD));
	}

	CString strNameTemp;
	if ( pInputData->dwLayersArray[0] == 1 && !bDisableInput )
	{	// v pripade, ze na vstupu nic neni (signal ma nula vrstev), nebo je vypnuty vstup
		try
		{
			strNameTemp = (WCHAR*)pInputData->pDataArrayArray[0][0];
		}
		catch(...)
		{
			strNameTemp = strName;
		}
		strName = strNameTemp;
	}
	DWORD dwErr = 0;
	DWORD dwLayer = 0;
	if ( -1 != strName.Find(L"%Layer%") )
		bLayerRqst = TRUE;
	do
	{
		CString value;
		CString strName2 = strName;
		value.Format(L"%08x", dwId);
		strName2.Replace(L"%id%", value);
		value.Format(L"%d", dwLayer);
		strName2.Replace(L"%layer%", value);
		HANDLE hFile = CreateFile(strName2, GENERIC_READ, FILE_SHARE_READ,
			NULL, OPEN_EXISTING, 0, NULL);
		if ( INVALID_HANDLE_VALUE != hFile )
		{
			CFile file(hFile);
			ULONGLONG llLen = file.GetLength();
			DWORD dwLen = (ULONG) llLen;
			if ( llLen != (ULONGLONG)dwLen )
			{	// chyba / soubor je vetsi jak 4GB
				CloseHandle(hFile);
				MessageBox(AfxGetMainWnd()->m_hWnd, L"File is bigger than 4GB", L"LoadFile - Error", MB_OK | MB_ICONERROR | MB_TASKMODAL);
				return S_FALSE;
			}
			void *data = malloc(dwLen);
			file.Read(data, dwLen);
			file.Close();
			dqLayers.push_back(std::pair<void*, DWORD>(data, dwLen));
			dwLayers++;
		}
		else
		{
			dwErr = GetLastError();
		}
		dwLayer++;
	} while ( dwErr != ERROR_FILE_NOT_FOUND && bLayerRqst );

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

STDMETHODIMP_(void) CImpBlock::Serialize(CArchive &ar)
{
	if ( ar.IsStoring() )
	{
		ar << m_strName << m_bCheckFile << m_bDisableInput << m_bSkipEmptyLayers;
	}
	else
	{
		ar >> m_strName >> m_bCheckFile >> m_bDisableInput >> m_bSkipEmptyLayers;
	}
}