#include <time.h>
#include "HtmlUtil.h"

#define OK 0

#define VPRINT if (verbose) printf

void usage();

static char buf[BUFSIZ+1];

int main(int argc, char **argv)
{
   char *host = "134.89.32.54";
   int c, sync = 0, verbose = 0;
   char *post = 0, *get = 0, *mode = 0;
   while ( (c = getopt(argc, argv, "h:g:p:m:tv")) != EOF )
   {
      switch (c) {
         case 'p':
         post = strdup(optarg);
         break;

         case 'h':
         host = strdup(optarg);
         break;

         case 'g':
         get = strdup(optarg);
         break;

         case 'm':
         mode = strdup(optarg);
         break;

         case 'v':
         verbose = 1;
         break;

         default:
         usage();
         return OK;

      }
   }

   // Check inputs
   //
   if ( ( post && !get ) || 
        ( mode  && (stricmp(mode, "record") && stricmp(mode, "data")) )  // Recognized modes
      )
   {
      usage();
      return 0;
   }

   HtmlUtil html(host);

   // Do sync request first if requested
   //
   // Removed from the command set (implemented by KiPro class)
   //
#if 0
   if (sync)
   {
      time_t now;
      time(&now);
      printf("Syncing time with Ki Pro Quad in %d seconds...\n",
              60 - (now % 60));
      c = html.time_sync();
      timespec ts, rem;
      clock_gettime(CLOCK_REALTIME, &ts);

      html.get_response(buf, BUFSIZ-1);
      VPRINT("%s\n", buf);

      VPRINT("%ld.%ld\n", ts.tv_sec, ts.tv_nsec);
      if (c != OK) return c;
   }
#endif

   if (post)
   {
      printf("Posting \'%s\' to Ki Pro Quad...\n", post);
      c = html.post(get, post);
      html.get_response(buf, BUFSIZ-1);
      VPRINT("%s\n", buf);
   }
   else if (get)
   {
      printf("Getting page \'%s\' from Ki Pro Quad...\n", get);
      c = html.get(get);
      html.get_response(buf, BUFSIZ-1);
      VPRINT("%s\n", buf);
   }

   else if (mode)
   {
      printf("Setting the mode of the Ki Pro Quad to \'%s\'...\n", mode);
      int m = stricmp(mode, "data")? 0 : 1; // Record = 0, Data = 1
      sprintf(buf, "config?action=set&paramid=eParamID_MediaState&value=%d", m);
      c = html.get(buf);
      html.get_response(buf, BUFSIZ-1);
      VPRINT("%s\n", buf);
   }

   if (c == OK)
   {
      printf("Normal successful completion\n");
   }
   else
   {
      printf("There was an issue\n");
   }

   return c;

}

void usage()
{
   fprintf(stderr, "USAGE: htmlget -h host  [-p post_page]  [-g get_page]  [-m mode]\n\
    \t     host: the website hostname. ex: coding.debuntu.org  default: modtronix\n \
    \tpost_page: the page code to post. ex: ?queryString=where\n \
    \t get_page: the page to retrieve. ex: index.html\n \
    \t     mode: \"record\" or \"data\" (case insensitive)\n");
}
     
     
