#include <iostream>
#include <cstring>
#include <bitset>
#include <unistd.h>
#include "HCNetSDK.h"
#include "HkStreamer.h"


void CALLBACK fPlayDataCallBack(LONG lPlayHandle, DWORD dwDataType, BYTE *pBuffer,DWORD dwBufSize,DWORD dwUser)
{
    if(dwBufSize>0){
      char pb[dwBufSize] = {0};
      memcpy(pb, pBuffer, dwBufSize);
      std::cout.write(pb, dwBufSize);
    }
    int pos = NET_DVR_GetDownloadPos(lPlayHandle);
    if (pos > 98)
    {
        fprintf(stderr, "pyd---Current Time:%d, data size:%d\n", time(NULL), dwBufSize);
        printf("Play over!%d\n", pos);
    }
}

int login(LPLoginInfo loginInfo)
{
  NET_DVR_Init();
  long lUserID;
  // login
  NET_DVR_USER_LOGIN_INFO struLoginInfo = {0};
  struLoginInfo.bUseAsynLogin = false;

  struLoginInfo.wPort = 8000;
  memcpy(struLoginInfo.sDeviceAddress, loginInfo->sDeviceAddress, NET_DVR_DEV_ADDRESS_MAX_LEN);
  memcpy(struLoginInfo.sUserName, loginInfo->sUserName, NAME_LEN);
  memcpy(struLoginInfo.sPassword, loginInfo->sPassword, NAME_LEN);
  lUserID = NET_DVR_Login_V40(&struLoginInfo, nullptr);
  return lUserID;
}
void cpTime(NET_DVR_TIME *nvrTime, StreamDate date){
  nvrTime->dwYear = date.dwYear;
  nvrTime->dwMonth = date.dwMonth;
  nvrTime->dwDay = date.dwDay;
  nvrTime->dwHour = date.dwHour;
  nvrTime->dwMinute = date.dwMinute;
  nvrTime->dwSecond = date.dwSecond;
}
int playback(LPLoginInfo loginInfo, LPStream stream)
{
  long lUserID = login(loginInfo);
  if (lUserID < 0)
  {
    printf("pyd1---Login error, %d\n", NET_DVR_GetLastError());
    return HPR_ERROR;
  }
  NET_DVR_VOD_PARA struVodPara = {0};
  StreamDate start = stream->start;
  cpTime(&struVodPara.struBeginTime, start);
  cpTime(&struVodPara.struEndTime, stream->end);
  int hPlayback = NET_DVR_PlayBackByTime_V40(lUserID, &struVodPara);
  if (hPlayback < 0)
  {
    printf("pyd1---PlayBack error, %d\n", NET_DVR_GetLastError());
    return HPR_ERROR;
  }

  if (!NET_DVR_SetPlayDataCallBack(hPlayback, fPlayDataCallBack, 1))
  {
    printf("NET_DVR_SetPlayDataCallBack fail!\n");
  }

  if (!NET_DVR_PlayBackControl(hPlayback, NET_DVR_PLAYSTART, 0, NULL))
  {
    printf("play back control failed [%d]\n", NET_DVR_GetLastError());
    return HPR_ERROR;
  }

  int pos = 0;
  for (pos = 0; pos < 100 && pos >= 0; pos = NET_DVR_GetDownloadPos(hPlayback))
  {
    sleep(10);
  }
  printf("have got %d\n", pos);
  if (!NET_DVR_StopGetFile(hPlayback))
  {
    printf("failed to stop get file [%d]\n", NET_DVR_GetLastError());
    return HPR_ERROR;
  }

  printf("StopGetFile\n");
  if (pos < 0 || pos > 100)
  {
    printf("download err [%d]\n", NET_DVR_GetLastError());
    return HPR_ERROR;
  }
  else
  {
    return 0;
  }

  // sleep(180); //˯3����
  NET_DVR_Logout_V30(lUserID);
  // cleanup
  NET_DVR_Cleanup();

  return HPR_OK;
}
int main()
{
}