
#include "stdafx.h"
#include "MultiZebrasDemo.h"
#include "MultiZebrasDemoDlg.h"
#include "FileOpenCombo.h"
#include "afxdialogex.h"

#include "AppGrabImages.h"

LPTSTR lpAnsi2lpWChar(LPSTR lpstr);
LPSTR  lpWChar2lpAnsi(LPTSTR lptstr);

#ifndef ZEBRAZ4U3DLLWIN32_EXPORTS
#include "ZebraZ4U3DllWin32.h"
#include "ImageFmtExchg.h"
#else

int getRunStepstate(__HZHANDLE__ hZhandle, PSRUNSTEPSTATE pRunStepState);
int GrabImageRequest(__HZHANDLE__ hZhandle, short imgStartIndx, short imgEndIndx, unsigned char imgGotOpCode, unsigned char bWaitSnapped);
int getPicture2File(__HZHANDLE__ hZhandle, char *pictureFileName, UCHAR *errCode);
ULONG getPicture2Buffer(__HZHANDLE__ hZhandle, unsigned char *pPicBuffer, ULONG pPicBufSiz, UCHAR *errCode);
#endif

void GrabImageData(void *pThis, __HZHANDLE__ hZhandle, int myId, int imgCnts, short imgStart, short imgEnding, TCHAR *pImgSavNmae)
{
	int				nRet;
	SRUNSTEPSTATE	sRunResult;
	CMultiZebrasDemoDlg *pMain = (CMultiZebrasDemoDlg *)pThis;
	TCHAR			szPrintStatus[256];
	BOOL            bRaw8To10;

	// Check image snapping state
	pMain->UpdateProgressMsg(myId, 20, NULL);
	bRaw8To10 = (pMain->m_chkRaw8To10.GetCheck() == BST_CHECKED);

	while ((nRet = getRunStepstate(hZhandle, &sRunResult)) > 0)
	{
		/* if (sRunResult.runResultState == __Sta_step_snapping__)
		sRunResult.resultType == __AppendData__
		sRunResult.appDataLen = 2;
		sRunResult.appendBuffer [0] = how many image are snapped
		sRunResult.appendBuffer [1] = has snapped images count
		*/
		if (sRunResult.runResultState == __Sta_None_Imgage__)
		{
			// error, no image pic is snapped
			//::PostMessage(m_hwndProgress, WM_MIPI_PROGRESS_MONITOR, IDC_PROGRESS_DOT, (LPARAM)L"Grab image");
			//::ShowWindow(m_hwndProgress, SW_HIDE);
			pMain->UpdateProgressMsg(myId, 100, L"Grabbed: no image picture");
			return;
		}
		else if (sRunResult.runResultState == __Sta_step_snapping__ && sRunResult.resultType == __AppendData__)
		{
			// sRunResult.appendBuffer [0] --- picture count
			// sRunResult.appendBuffer [1] --- snapped pictured count
			if (sRunResult.appendBuffer[0] != imgCnts)
			{
				pMain->UpdateProgressMsg(myId, 100, L"Grabbed: image count conflict?");
				return;
			}
			if (sRunResult.appendBuffer[1] > imgStart && sRunResult.appendBuffer[1] > imgEnding)
			{
				// target image has receviced!
				break;
			}
			else
				continue;
		}
		else if (sRunResult.runResultState == __Sta_step_succeed__ && sRunResult.resultType == __SnapPicture__)
		{
			// sRunResult.snapCnt :: image picture count
			// sRunResult.pSnaPicSiz[i] = size of every picture
			if (sRunResult.snapCnt != imgCnts)
			{
				pMain->UpdateProgressMsg(myId, 100, L"Grabbed: image count conflict?");
				return;
			}
			break;
		}
	}	// while Checking 

	if (nRet != TRUE)
	{
		pMain->UpdateProgressMsg(myId, 100, L"Grabbed: can't get Zebra run-step status");
		return;
	}
	//
	pMain->UpdateProgressMsg(myId, 30, NULL);

	// Get from assigned index to last 
	if (sRunResult.runResultState == __Sta_step_succeed__ && sRunResult.resultType == __SnapPicture__)
	{
		int			k, percnt;
		char		*pszBuf;
		UCHAR		errCode;
		SYSTEMTIME	LocalTime;
		TCHAR		szBmpFileName[MAX_PATH];

		GrabImageRequest(hZhandle, imgStart, imgEnding, __Grab_opt_noneOperation__, 1);	//	to wait

		pMain->UpdateProgressMsg(myId, percnt = 50, NULL);
		// Here only show none image extra operation, to get assigned pictures
		for (k = imgStart; k <= imgEnding; k++)
		{
			// Generate a new capture file name by datetime
			GetLocalTime(&LocalTime);
			swprintf(szBmpFileName, L"%s%02d%02d-%02d%02d%02d.%03d.raw", pImgSavNmae, LocalTime.wMonth, LocalTime.wDay, LocalTime.wHour, LocalTime.wMinute, LocalTime.wSecond, LocalTime.wMilliseconds);

			////////////////////////////////////////////////
			if (k % 2)	// only for test getPicture2File and getPicture2Buffer
			{
				UCHAR *pPic;
				ULONG  uPicGotSiz;
				//
				pPic = (UCHAR *)malloc(sRunResult.pSnaPicSiz[k]);
				uPicGotSiz = getPicture2Buffer(hZhandle, pPic, sRunResult.pSnaPicSiz[k], &errCode);
				if (uPicGotSiz)
				{
					HANDLE hFile = CreateFile(szBmpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

					if (bRaw8To10)
					{
						UCHAR *pPicRaw10;
						ULONG  uRaw10Size;
						int     errExchg;

						pPicRaw10 = RawStrmToRaw10(pPic, uPicGotSiz, &uRaw10Size, &errExchg);
						if (errExchg == __NO_ERROR_EXCHG__)
						{
							if (hFile != INVALID_HANDLE_VALUE)
							{
								DWORD wrLen;
								WriteFile(hFile, pPicRaw10, uRaw10Size, &wrLen, NULL);
								CloseHandle(hFile);
							}
							freeRawExchgBuffer(pPicRaw10);
						}
					}
					else
					{
						if (hFile != INVALID_HANDLE_VALUE)
						{
							DWORD wrLen;
							WriteFile(hFile, pPic, uPicGotSiz, &wrLen, NULL);
							CloseHandle(hFile);
						}
					}
				}
				free(pPic);
			}
			else
			{
				// directly save to file!
				char *pBmpFileName = NULL;
				
				getPicture2File(hZhandle, pBmpFileName = lpWChar2lpAnsi(szBmpFileName), &errCode);

				if (errCode)
				{
					if (__Error_snapping__ != errCode)	// if snapping try get once
						break;							// error to break

					do
					{
						Sleep(100);			// Wait till data got
					} while (getPicture2File(hZhandle, pBmpFileName , &errCode) && errCode == __Error_snapping__);
				}	// while - image still snapping ...

				if (bRaw8To10)
				{
					FILE *fileRaw8;
					UCHAR *pRaw8Data, *pRaw10Data;

					if (fileRaw8 = fopen(pBmpFileName, "r+b"))	// read and write
					{
						long fileSiz;

						fseek(fileRaw8, 0, SEEK_END);
						fileSiz = ftell(fileRaw8);
						fseek(fileRaw8, 0, SEEK_SET);

						pRaw8Data = (UCHAR *)malloc(fileSiz);
						if (pRaw8Data)
						{
							int lrdItem = fread(pRaw8Data, fileSiz, 1, fileRaw8);

							if (lrdItem)
							{
								ULONG uRaw10Size;
								int   errExchg;

								pRaw10Data = RawStrmToRaw10(pRaw8Data, fileSiz, &uRaw10Size, &errExchg);
								if (errExchg == __NO_ERROR_EXCHG__)
								{
									fseek(fileRaw8, 0, SEEK_SET);
									fwrite(pRaw10Data, uRaw10Size, 1, fileRaw8);

									freeRawExchgBuffer(pRaw10Data);
								}
							}
							free(pRaw8Data);
						}
						fclose(fileRaw8);
					}
				}

				if (pBmpFileName) free(pBmpFileName);

			}	// if - for test getPicture2File or getPicture2Buffer

			if (percnt < 90)
				percnt += 10;
			pMain->UpdateProgressMsg(myId, percnt, NULL);
		}	// for - get all images
	}

	swprintf(szPrintStatus, L"Grabbed: images from %d to %d are got, total %d pictures, save to %sMMDD-HHmmSS.sss.raw!", imgStart, imgEnding, (imgEnding - imgStart + 1), pImgSavNmae);
	pMain->UpdateProgressMsg(myId, 100, szPrintStatus);
}
