#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <timecode/timecode.h>

/* test sample
 * 08:17:00:23  1352017021.063243775
 */

Timecode tc;
char * fmt = NULL;

static struct option const long_options[] =
{
	{"help", no_argument, 0, 'h'},
	{"format", required_argument, 0, 'F'},
	{"fps", required_argument, 0, 'f'},
	{"version", no_argument, 0, 'V'},
	{NULL, 0, NULL, 0}
};

static void usage (int status) {
  printf ("sec2time - parse seconds or unixtime to A/V timecode.\n\n");
  printf ("Usage: sec2time [ OPTIONS ] time\n\n");
  printf ("Options:\n\
  -f, --fps <num>[/den]      set framerate (default 1000/1)\n\
  -F, --format <fmt>         describe output format\n\
  -h, --help                 display this help and exit\n\
  -V, --version              print version information and exit\n\
\n");
  printf ("\n\
...\n\
\n\
...\n\
\n");
  printf ("Report bugs to Robin Gareus <robin@gareus.org>\n"
          "Website and manual: <https://github.com/x42/timecode-utils>\n"
	  );
  exit (status);
}

static int decode_switches (int argc, char **argv) {
  int c;

  while ((c = getopt_long (argc, argv,
			   "F:"	/* format*/
			   "f:"	/* fps */
			   "h"	/* help */
			   "V",	/* version */
			   long_options, (int *) 0)) != EOF)
    {
      switch (c) {

	case 'F':
	  if (fmt) free(fmt);
		fmt=strdup(optarg);
	  break;

	case 'f':
		timecode_parse_framerate(&tc.r, optarg, 0);
	break;

	case 'V':
	  printf ("sec2time version %s\n\n", VERSION);
	  printf ("Copyright (C) GPL 2012 Robin Gareus <robin@gareus.org>\n");
	  exit (0);

	case 'h':
	  usage (0);

	default:
	  usage (EXIT_FAILURE);
	}
    }

  return optind;
}

int main (int argc, char **argv) {
	char tme[1024];
	timecode_copy_rate(&tc, TCFPSMS);
	timecode_reset_unixtime(&tc);

	int i = decode_switches(argc, argv);
	if (i >= argc) usage (EXIT_FAILURE);

	double unixtime = strtod(argv[i], NULL);
	printf ("unixtime: %f\n", unixtime);

	timecode_seconds_to_time(&tc.t, &tc.r, unixtime);

	if (!fmt) {
		if (tc.t.hour <= 24 ) {
			fmt=strdup("%T");
		} else {
			fmt=strdup("%Z");
		}
	}

	tc.d.day = 1 + tc.t.hour/24;
	timecode_move_date_overflow(&tc.d);
	tc.t.hour = tc.t.hour%24;

	timecode_strftimecode(tme, 1024, fmt, &tc);
	tme[1023]='\0';
	printf("%s\n", tme);

	free(fmt);
	return 0;
}
