#include "XNetSDKTest.h"

int CALLBACK Test_DownloadByNameCallBack(XSDK_HANDLE hMedia, const unsigned char *pData, int nDataLen, int nDataType, void *pDataInfo, int nDataInfoSize, void *pUserData)
{
	static int nDownload = 0;
	if (EXCMD_DOWNLOAD_DATA == nDataType && nDataLen > 0)
	{
		char name[200] = {0};
		sprintf(name, "%d.jpg", 1);
		printf("DataLen = %d\r\n", nDataLen);

		////////设备下载的图片一般会含有16个字节头需要去除//////////////
		if(nDownload == 0)
		{
			pData += 16;
			nDataLen -= 16;
		}

		FILE *file = fopen(name, "ab+");
		if (file)
		{
			fwrite(pData, 1, nDataLen, file);
			fclose(file);
		}

		nDownload++;
	}
	else if (ESXSDK_MEDIA_DOWN_RECORD_FILE == nDataType)
	{
		printf("OnRecordDownloadResult[%d][%s]\r\n", hMedia, nDataLen >= 0 ? "Success" : "Failed");
	}
	else if(ESXSDK_MEDIA_ON_PLAY_STATE == nDataType)
	{
		printf("Media[hMedia:%ld][ESXSDK_MEDIA_ON_PLAY_STATE:%d][EMediaChnState:%d]\r\n", hMedia, nDataLen);
		if (nDataLen == EState_Media_DataEnd)
		{
			nDownload = 0;
			printf("OnRecordDownloadResult Complete!\r\n");
		}
	}
	else
	{
		printf("Media[hMedia:%ld][Len:%d][Type:%d]\r\n", hMedia, nDataLen, nDataType);
	}
	return 0;
}

int TestDownloadByName()
{
	printf("%s\r\n", __FUNCTION__);
	XSDK_HANDLE hPlayer = 0;
	char c = 0;
	do
	{
		switch(c)
		{
		case 's':
			{
				if (hPlayer)
				{
					XSDK_MediaStop(hPlayer);
					hPlayer = 0;
				}

				if(!bFindFile)
				{
					printf("No file!\r\n");
					break;
				}

				SXMediaRecordByFileReq param = {0};
				param.nChannel = 0;
				param.pMediaCallback = Test_DownloadByNameCallBack;
				
				strcpy(param.sBeginTime, info.sBeginTime);
				strcpy(param.sEndTime, info.sEndTime);
				strcpy(param.sFileName, info.sFileName);

				hPlayer = XSDK_MediaRecordDownloadByName(g_hDevice, &param, 0, 4000);
			}
			break;
		case 't':
			{
				XSDK_MediaStop(hPlayer);
				hPlayer = 0;
			}
			break;
		}
	}while((c = getchar()) != 'q');

	if (hPlayer)
	{
		XSDK_MediaStop(hPlayer);
		hPlayer = 0;
	}
	return 0;
}