#include "HkStreamer.h"
#include <iostream>
#include <cstring>
#include <map>
#include <getopt.h>
#include <time.h>
using namespace std;
bool check_key(std::map<std::string, std::string> *m, string key)
{
  // Key is not present
  if (m->find(key) == m->end())
    return false;

  return true;
}

void parseTime(string timeStr,struct tm *timeOut){
  strptime(timeStr.c_str(), "%Y%m%dT%H%M%S",timeOut);
}
void parseArgs(int argc, char *argv[], std::map<std::string, std::string> *paramMap)
{
  static struct option long_options[] = {
      {"cnd", required_argument, NULL, 'c'},
      {"url", required_argument, NULL, 'i'},
      {"user", required_argument, NULL, 'u'},
      {"passwd", required_argument, NULL, 'p'},
      {"device", required_argument, NULL, 'd'},
      {"channel", required_argument, NULL, 'c'},
      {"start", required_argument, NULL, 's'},
      {"end", required_argument, NULL, 'e'},
  };
  int c;
  while (1)
  {
    int opt_index = 0;
    c = getopt_long(argc, argv, "c:u:p:", long_options, &opt_index);
    if (c == -1)
    {
      break;
    }

    std::string paraName(1, char(c));

    std::cout << "paraName:" << paraName << std::endl;
    std::string paraValue = optarg;

    (*paramMap)[paraName] = paraValue;
  }
}

void error(string msg)
{
  cerr << msg << endl;
  exit(1);
}

int main(int argc, char *argv[])
{
  std::map<std::string, std::string> pMap;
  parseArgs(argc, argv, &pMap);
  std::string cmd = pMap.at("cmd");
  if (!check_key(&pMap, "u"))
  {
    error("Must set user");
  }

  if (!check_key(&pMap, "d"))
  {
    error("Must set device address");
  }
  LoginInfo loginInfo = {0};
  strcpy(loginInfo.sDeviceAddress, pMap.at("d").c_str());
  strcpy(loginInfo.sUserName, pMap.at("u").c_str());
  strcpy(loginInfo.sPassword, pMap.at("p").c_str());
  if (cmd == "playback")
  {
    if (!check_key(&pMap, "c"))
    {
      error("Muset set channel");
    }

    if (!check_key(&pMap, "s"))
    {
      error("Must set start time");
    }
    if (!check_key(&pMap, "e"))
    {
      error("Must set end time");
    }

    StreamCon stream = {0};

    stream.lChannel = stol(pMap.at("c"));
    string startStr = pMap.at("s");
    struct tm start;
    parseTime(startStr, &start);
    stream.start.dwYear = start.tm_year;
    stream.start.dwMonth = start.tm_mon;
    stream.start.dwDay = start.tm_mday;
    stream.start.dwHour = start.tm_hour;
    stream.start.dwMinute = start.tm_min;
    stream.start.dwSecond = start.tm_sec;
    string endStr = pMap.at("e");
    struct tm end;
    parseTime(endStr, &end);
    stream.end.dwYear = end.tm_year;
    stream.end.dwMonth = end.tm_mon;
    stream.end.dwDay = end.tm_mday;
    stream.end.dwHour = end.tm_hour;
    stream.end.dwMinute = end.tm_min;
    stream.end.dwSecond = end.tm_sec;
    playback(&loginInfo, &stream);
   
  }
  // getCfg(&loginInfo);
  return 0;
}
