/******************************************************************************
 *
 *                Copyright (c) 2017-2019 by Löwenware Ltd
 *             Please, refer LICENSE file for legal information
 *
 ******************************************************************************/

/**
 * @file compose.c
 * @author Ilja Kartašov <ik@lowenware.com>
 * @brief 
 *
 * @see https://lowenware.com/
 */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <components/html.h>

#include "option.h"
#include "compose.h"


static int
compose_help(void)
{
	printf("NAME\n");
	printf("\taisl-compose - Compose plain text resource\n\n");
	printf("SYNOPSIS\n");
	printf("\taisl compose [--format=auto|html|js|css] <source> <target>\n\n");
	printf("DESCRIPTION\n");
	printf("\tComposes a plain text resource to its production version.");
	printf("OPTIONS\n");
	printf("\t--format=auto|html|js|css\n");
	printf("\t    Manually set format for the composer. Usefull when file "
			"extension does not allow to determine type automatically.\n\n");
	return 0;
}


int
compose_execute(int argc, char **argv)
{
	int result;
	struct cstuff_list list;
	struct ax_html_options opts = {0};

	if (g_options & OPTION_FLAG_HELP) {
		return compose_help();
	}

	result = -1;

	if (!(argc == 1 || argc == 2)) {
		return result;
	}

	g_source = argv[0];

	if (argc == 2) {
		g_target = argv[1];
	}

	opts.offset = "\t";
	opts.path = g_target ? g_target : ".";
	opts.name = "html";
	opts.minimize = true;

	if (!cstuff_list_init(&list, 128)) {
		if (ax_html_import(&list, g_source) == AISL_SUCCESS) {
			if (ax_html_export(&list, &opts) == AISL_SUCCESS) {
				result = 0;
			} else {
				fprintf(stderr, "Export failed\n");
			}
		} else {
			fprintf(stderr, "Import failed: %s\n", strerror(errno));
		}
		cstuff_list_release(&list, (CStuffListFree)ax_html_free);
	}

	return result;
}
