/* main.c
 * This file is part of Amsam photo cropping program
 * Copyright 2021, 2023, 2024, 2025, 2026 Nandakumar Edamana
 * Distributed under GNU General Public License, version 3
 */ 

#include <assert.h>
#include <stdarg.h>
#include <stdbool.h>

#include "main.h"


int main(int argc, char * *argv)
{
	Test testtype = TEST_NONE;

	int test_nongui_count = 1000;

	_Bool test_vara_logo_exit = false;
	int test_vara_logo_size = 256;

	const char *infile_path = NULL;

	int argi = 1;
	while (argi < argc) {
		if (0 == strcmp(argv[argi], "--test")) {
			testtype = TEST_UI;
		} else if (0 == strcmp(argv[argi], "--test-nongui")) {
			testtype = TEST_NONGUI;
		} else if (0 == strcmp(argv[argi], "--test-nongui-count")) {
			test_nongui_count = get_positive_intarg(argv[argi], argc, argv, argi);
			argi += 1;
		} else if (0 == strcmp(argv[argi], "-v")) {
			jpeg_log_enabled = true;
		} else if (0 == strcmp(argv[argi], "--version")) {
			printf("%s %s\n", PROGRAM_NAME, VERSION);
			exit(EXIT_SUCCESS);
		} else {
			if (argi == argc - 1) {
				infile_path = argv[argi];
			} else {
				fprintf(stderr, "%s: unknown command-line option: %s\n", argv[0], argv[argi]);
				exit(EXIT_FAILURE);
			}
		}

		argi += 1;
	}

	switch (testtype) {
	case TEST_NONGUI:
	{
		return testmain_nongui(test_nongui_count);
		break;
	}

	default: {
		break;
	}
	}

	gtk_init(0, NULL);

	myapp *app = (myapp *) malloc(sizeof(myapp));
	if (app == NULL) {
		perror(NULL);
		exit(EXIT_FAILURE);
	}

	myapp_construct(app, infile_path);

	ProceduralGuiTestingContext *tctx = NULL;

	switch (testtype) {
	case TEST_NONE:
	{
		break;
	}

	case TEST_UI:
	{
		testmain_general(app);
		break;
	}

	case TEST_SUNSET:
	{
		assert(!tctx);
		ProceduralGuiTestingContext *_ngg_tmp_2 = testmain_sunset(app);
		if (tctx) {
			procedural_gui_testing_context_destruct((ProceduralGuiTestingContext *) tctx);
			free(tctx);
		}

		tctx = _ngg_tmp_2;
		break;
	}

	case TEST_VARALOGO:
	{
		app->test_vara_logo_exit = test_vara_logo_exit;
		app->test_vara_logo_size = test_vara_logo_size;
		testmain_draw_vara_logo(app);
		break;
	}

	case TEST_NONGUI:
	{
		break;
	}
	}

	gtk_main();

	if (app) {
		myapp_destruct(app);
		free(app);
	}

	if (tctx) {
		procedural_gui_testing_context_destruct((ProceduralGuiTestingContext *) tctx);
		free(tctx);
	}

	return 0;
}

int get_positive_intarg(const char *argstr, int argc, char * *argv, int argi)
{
	int argval = 0;

	if (argi + 1 >= argc) {
		fprintf(stderr, "%s: %s expects argument\n", argv[0], argstr);
		exit(EXIT_FAILURE);
	}

	argval = atoi(argv[argi + 1]);
	if (argval < 1) {
		fprintf(stderr, "%s: %s expects a positive integer\n", argv[0], argstr);
		exit(EXIT_FAILURE);
	}

	return argval;
}
