/* Copyright (C) 2013 G.P. Halkes
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License version 3, as
   published by the Free Software Foundation.

   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 <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <float.h>
#include <time.h>
#include <errno.h>

#include "common.h"
#include "optionMacros.h"
#include "replay.h"
#include "input.h"

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
#include "write_stringlist.h"
#endif

static const char *inputA, *inputB;
static ExpNode *scriptA, *scriptB;
static td_bool stop_on_difference;
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static td_bool describe;
static td_bool visual_compare;
static window_t *winA, *winB;
#ifdef HAVE_CAIRO
static const char *picture_name;
static const char *picture_series;
#endif
#endif

// FIXME: add option to check equality of sent strings as well

static void printUsage(void) {
	printf("Usage: tdcompare [OPTIONS] <recording A> <recording B>\n");
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	printf("  -v, --visual-compare                Check for visual equality\n");
	printf("  -D, --describe                      Print a description of the first\n"
	       "                                        difference found\n");
#ifdef HAVE_CAIRO
	printf("  -p<name>, --picture=<name>          Write a picture of the differences to\n"
	       "                                        <name>\n");
	printf("  -f<font>, --font=<font>             Use <font> to show text in picture.\n");
	printf("  -W<width>, --cell-width=<width>     Use <width> as cell width in picture.\n");
	printf("  -H<height>, --cell-height=<height>  Use <height> as cell width in picture.\n");
	printf("  -P<name>, --picture-series=<name>   Create a series of picutes use <name> as\n"
	       "                                        template\n");
	printf("  -s, --stop-on-difference            Stop when the first visual difference is\n"
	       "                                        found\n");
#endif
#endif
	printf("  -V, --version                       Print version and copyright information\n");
	exit(EXIT_SUCCESS);
}

static PARSE_FUNCTION(parse_options)
	OPTIONS
		OPTION('h', "help", NO_ARG)
			printUsage();
		END_OPTION
		OPTION('V', "version", NO_ARG)
			fputs("tdcompare " VERSION_STRING "\nCopyright (C) 2013 G.P. Halkes\nLicensed under the GNU General Public License version 3\n", stdout); /* @copyright */
			exit(0);
		END_OPTION
		OPTION('v', "visual-compare", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			visual_compare = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('D', "describe", NO_ARG)
#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
			describe = td_true;
#else
			fatal("termdebug was built without (n)curses and/or libunistring, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('p', "picture", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			picture_name = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('f', "font", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			option_font = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('W', "cell-width", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 16);
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('H', "cell-heigth", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			PARSE_INT(cell_width, 6, 24);
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('P', "picture-series", REQUIRED_ARG)
#ifdef HAVE_CAIRO
			if (!check_fmt(optArg))
				fatal(OPTFMT " argument must have exactly one d-type printf conversion\n", OPTPRARG);
			picture_series = optArg;
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION
		OPTION('s', "stop-on-difference", NO_ARG)
#ifdef HAVE_CAIRO
			stop_on_difference = td_true;
#else
			fatal("termdebug was built without cairo, and therefore tdcompare does not provide " OPTFMT "\n", OPTPRARG);
#endif
		END_OPTION

		DOUBLE_DASH
			NO_MORE_OPTIONS;
		END_OPTION

		fatal("Unknown option " OPTFMT "\n", OPTPRARG);
	NO_OPTION
		if (inputA != NULL) {
			if (inputB != NULL)
				fatal("More than two recordings specified\n");
			inputB = optcurrent;
		} else {
			inputA = optcurrent;
		}
	END_OPTIONS
	if (inputA == NULL || inputB == NULL)
		fatal("Two recordings should be specified\n");
#ifdef HAVE_CAIRO
	if (picture_series == NULL)
		stop_on_difference = td_true;
#else
	stop_on_difference = td_true;
#endif
END_FUNCTION

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
static td_bool advance_script(ExpNode **script, window_t *win) {
	while (*script != NULL) {
		switch ((*script)->type) {
			case EXP_START:
			case EXP_INTERACT:
			case EXP_ENV:
				/* Ignore stuff that isn't relavant to simply viewing the replay. */
				break;
			case EXP_EXPECT:
				win_write_stringlist(win, (*script)->un.args);
				break;
			case EXP_SEND:
				*script = (*script)->next;
				return td_true;
			case EXP_EXPECT_EXIT:
				*script = (*script)->next;
				return td_true;
			case EXP_WINDOW_SIZE:
				win_resize(win, (*script)->un.size.rows, (*script)->un.size.columns);
				*script = (*script)->next;
				return td_true;
			case EXP_EXPECT_SUSPEND:
				win_set_paint(win, 0, 0);
				win_clrtobot(win);
				return td_true;
			case EXP_REQUIRE_VERSION:
				break;
			default:
				fatal("Internal error\n");
		}
		*script = (*script)->next;
	}
	return td_false;
}

static void do_visual_compare(void) {
	td_bool difference_reported = td_false;
	const char *winAterm, *winBterm;
	int step_count = 0;

	init_attr_map();

	if ((winA = win_new(24, 80)) == NULL)
		fatal("Out of memory\n");
	if ((winB = win_new(24, 80)) == NULL)
		fatal("Out of memory\n");

	winAterm = get_script_env(scriptA, "TERM");
	winBterm = get_script_env(scriptB, "TERM");
	if (winAterm == NULL)
		fatal("Recording %s does not contain a TERM environment variable\n", inputA);
	if (winBterm == NULL)
		fatal("Recording %s does not contain a TERM environment variable\n", inputB);
	if (strcmp(winAterm, winBterm) != 0)
		fatal("Recordings have a different TERM environment variable\n");
	setup_ti_strings(winAterm, get_script_env(scriptA, "LANG"));

	while (td_true) {
		if (!advance_script(&scriptA, winA))
			break;
		if (!advance_script(&scriptB, winB))
			break;

#ifdef HAVE_CAIRO
		if (picture_series != NULL) {
			char output_name_buffer[1024];
			snprintf(output_name_buffer, sizeof(output_name_buffer), picture_series, step_count);
			win_write_image(winA, winB, output_name_buffer);
		}
#endif

		if (!win_compare(winA, winB, describe ? stderr : NULL)) {
#ifdef HAVE_CAIRO
			if (picture_name != NULL) {
				win_write_image(winA, winB, picture_name);
				picture_name = NULL;
			}
#endif
			if (!difference_reported) {
				fprintf(stderr, "Recordings have different results\n");
				difference_reported = td_true;
			}
			/* stop_on_difference will be set to false if picture_series == NULL. */
			if (stop_on_difference)
				exit(EXIT_FAILURE);
			describe = td_false;
		}
		step_count++;
	}

	if (scriptA != scriptB && !difference_reported)
		fatal("Recordings have different results\n");

	free_attr_map();
}
#endif

static ExpNode *find_start(ExpNode *script) {
	for (; script != NULL && script->type != EXP_START; script = script->next) {}
	return script;
}

static void compare_expects(void) {
	StringListNode *stringA = scriptA->un.args;
	StringListNode *stringB = scriptB->un.args;
	int stringA_offset = 0;
	int stringB_offset = 0;
	int min_length;


	while (1) {
		min_length = MIN(stringA->length - stringA_offset, stringB->length - stringB_offset);
		/* FIXME: explain which string and at which offset */
		if (memcmp(stringA->string + stringA_offset, stringB->string + stringB_offset, min_length) != 0)
			fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line);
		stringA_offset += min_length;
		if (stringA->length <= stringA_offset) {
			stringA = stringA->next;
			stringA_offset = 0;
		}
		stringB_offset += min_length;
		if (stringB->length <= stringB_offset) {
			stringB = stringB->next;
			stringB_offset = 0;
		}

		if (stringA == NULL && stringB == NULL) {
			scriptA = scriptA->next;
			scriptB = scriptB->next;
			return;
		}

		if (stringA == NULL) {
			/* FIXME: explain which string and at which offset */
			if (scriptA->next->type != EXP_EXPECT)
				fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line);
			scriptA = scriptA->next;
			stringA = scriptA->un.args;
		}
		if (stringB == NULL) {
			/* FIXME: explain which string and at which offset */
			if (scriptB->next->type != EXP_EXPECT)
				fatal("Different strings expected at %d/%d\n", scriptA->line, scriptB->line);
			scriptB = scriptB->next;
			stringB = scriptB->un.args;
		}
	}
}

static void compare(void) {
	static const char *exp2string[] = {
		"start", "env", "window_size", "expect", "send", "expect_exit",
		"interact", "expect_suspend", "require_version"
	};

	scriptA = find_start(scriptA);
	scriptB = find_start(scriptB);

	if (scriptA == NULL)
		fatal("Recording '%s' does not have a start directive\n", inputA);
	if (scriptB == NULL)
		fatal("Recording '%s' does not have a start directive\n", inputB);

	while (scriptA != NULL && scriptB != NULL) {
		if (scriptA->type != scriptB->type)
			fatal("Recordings have different actions (%s/%s) at line %d/%d\n",
				exp2string[scriptA->type], exp2string[scriptB->type],
				scriptA->line, scriptB->line);

		switch (scriptA->type) {
			case EXP_START:
			case EXP_INTERACT:
				/* Ignore stuff that isn't relavant to simply viewing the replay. */
				break;
			case EXP_EXPECT:
				compare_expects();
				break;
			case EXP_SEND:
				break;
			case EXP_WINDOW_SIZE:
				if (scriptA->un.size.columns != scriptB->un.size.columns ||
						scriptA->un.size.rows != scriptB->un.size.rows)
					fatal("Recordings set different window size (%dx%d/%dx%d) at line %d/%d\n",
						scriptA->un.size.columns, scriptA->un.size.rows,
						scriptB->un.size.columns, scriptB->un.size.rows,
						scriptA->line, scriptB->line);
				break;
			case EXP_EXPECT_EXIT:
				if (scriptA->un.number != scriptB->un.number)
					fatal("Expecting different exit value (%d/%d) at line %d/%d\n",
						scriptA->un.number, scriptB->un.number, scriptA->line, scriptB->line);
				break;
			case EXP_EXPECT_SUSPEND:
				break;
			default:
				fatal("Internal error\n");
		}

		scriptA = scriptA->next;
		scriptB = scriptB->next;
	}
}

int tdcompare_main(int argc, char *argv[]) {

	parse_options(argc, argv);

	reset_lexer(inputA);
	parse();
	scriptA = script;
	script = NULL;

	reset_lexer(inputB);
	parse();
	scriptB = script;

#if defined(HAVE_CURSES) && defined(HAVE_UNISTRING)
	if (visual_compare)
		do_visual_compare();
	else
#endif
		compare();
	return EXIT_SUCCESS;
}
