/*
 * Copyright (C) 2024  Tristan Riehs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 */
#include "config.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "_readline.h"
static int lower = 0;
static int upper = 100;
static FILE *logfile;
static char logbuf[64];
#define LOGBUF_OFFSET 11
/* Return a random number x such that lower <= x < upper. */
static int
calculer_rand(void)
{
	return lower + rand()%(upper-lower);
}
/* Compute the number of milliseconds TP contains. */
static intptr_t
tp_ms(struct timespec const *tp)
{
	return tp->tv_sec*1000 + tp->tv_nsec/1000000;
}
/* Called just before prompting the user. The returned pointer will be given
   back as a parameter of measure_after. */
static void *
measure_before(void)
{
	struct timespec tp;
	clock_gettime(CLOCK_REALTIME, &tp);
	return (void *)tp_ms(&tp);
}
/* Called just after the user prompt has been read and checked. */
int
measure_after(void *data, int correct)
{
	int t0 = (intptr_t) data;
	struct timespec tp;
	clock_gettime(CLOCK_REALTIME, &tp);
	int t1 = tp_ms(&tp);
	int dt = t1 - t0;
	size_t bytes_written =
		LOGBUF_OFFSET + sprintf(logbuf + LOGBUF_OFFSET,
					"%d\t%d\n", dt, correct);
	return bytes_written != fwrite(logbuf, 1, bytes_written, logfile);
}
/* Only use in print_usage. */
#define print_opt_noarg(opt, desc) \
	fprintf(stream, "  -"opt"\t\t"desc"\n")
/* Only use in print_usage. */
#define print_opt_arg(opt, arg, desc) \
	fprintf(stream, "  -"opt" "arg"\t"desc"\n");
void
print_usage(FILE *stream)
{
	fprintf(stream, "Usage: calculer [OPTIONS]\n");
	fprintf(stream, "OPTIONS\n");
	print_opt_noarg("V", "Print version and exit.");
	print_opt_noarg("h", "Print help and exit.");
	print_opt_arg("l", "LOGFILE", "Use LOGFILE as log file.\n");
	print_opt_arg("m", "MIN",
		      "Set MIN as the minimum value numbers can take.\n");
	print_opt_arg("M", "MAX",
		      "Set MAX as the maximum value numbers can take.\n");
}
void
print_help(void)
{
	printf("calculer -- train mental calculus\n");
	printf("calculer is licensed under the GPL3 License.\n");
	print_usage(stdout);
}
void
print_version(void)
{
	printf("%s\n", VERSION);
}
int
main(int argc, char *argv[])
{
	char *logpath = "./calculer.log";
	srand(time(NULL));
	/* Store the prefix "YYYY-MM-DD" in LOGBUF. */
	time_t now = time(NULL);
	struct tm *tm = localtime(&now);
	size_t bytes_written = strftime(logbuf, sizeof(logbuf), "%F\t", tm);
	assert(bytes_written);
	int opt;
	while ((opt = getopt(argc, argv, ":Vhl:m:M:")) != -1)
	{
		switch (opt)
		{
		case 'V':
			print_version();
			exit(0);
		case 'h':
			print_help();
			exit(0);
		case 'l':
			logpath = optarg;
			break;
		case 'm':
			lower = atoi(optarg);
			break;
		case 'M':
			upper = atoi(optarg);
			break;
		case ':':
			fprintf(stderr,
				"calculer: option %d requires an argument\n",
				optopt);
			print_usage(stderr);
			exit(1);
		default:
			print_usage(stderr);
			exit(1);
		}
	}
	logfile = fopen(logpath, "a");
	assert(logfile);
	while (1)
	{
		char prompt[32] = {0};
		int x, y, res;
		char *input;
		int input_val;
		x = calculer_rand();
		y = calculer_rand();
		res = x+y;
		sprintf(prompt, "%d + %d = ", x, y);
		void *measure_data = measure_before();
		input = readline(prompt);
		if ((!input) || (*input == '\0'))
		{
			free(input);
			fclose(logfile);
			exit(0);
		}
		input_val = atoi(input);
		if (measure_after(measure_data, input_val == res))
		{
			free(input);
			fclose(logfile);
			exit(1);
		}
		if (input_val == res)
			printf("RIGHT\n");
		else
			printf("WRONG\n");
		free(input);
	}
	fclose(logfile);
	return 0;
}