/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - svg export
 *  Copyright (C) 2022, 2024 Tibor 'Igor2' Palinkas
 *
 *  (Supported by NLnet NGI0 PET Fund in 2022)
 *
 *  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 2 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, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *  Contact:
 *    Project page: http://repo.hu/projects/sch-rnd
 *    contact lead developer: http://www.repo.hu/projects/sch-rnd/contact.html
 *    mailing list: http://www.repo.hu/projects/sch-rnd/contact.html
 */

#include <libcschem/config.h>

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <genvector/gds_char.h>

#include <librnd/core/math_helper.h>
#include <librnd/core/rnd_conf.h>
#include <librnd/core/error.h>
#include <librnd/core/misc_util.h>
#include <librnd/core/compat_misc.h>
#include <librnd/core/plugins.h>
#include <librnd/core/safe_fs.h>
#include <librnd/hid/hid.h>
#include <librnd/hid/hid_nogui.h>
#include <librnd/hid/hid_init.h>
#include <librnd/hid/hid_attrib.h>
#include <librnd/plugins/lib_exp_text/draw_svg.h>

#include <libcschem/concrete.h>
#include <libcschem/util_export.h>

#include <sch-rnd/draw.h>
#include <sch-rnd/export.h>


static rnd_hid_t svg_hid;

const char *svg_cookie = "export_svg";

static rnd_svg_t pctx_, *pctx = &pctx_;

static const char *colorspace_names[] = {
	"color",
	"grayscale",
	"monochrome",
	NULL
};

static const rnd_export_opt_t svg_attribute_list[] = {
	{"outfile", "Graphics output file",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_svgfile 0

	{"opacity", "Layer opacity",
	 RND_HATT_INTEGER, 0, 100, {100, 0, 0}, 0},
#define HA_opacity 1

	{"screen-colors", "Allow object highlight and selection color",
	 RND_HATT_BOOL, 0, 0, {0, 0, 0}, 0},
#define HA_screen_color 2

	{"true-size", "Attempt to preserve true size for printing",
	 RND_HATT_BOOL, 0, 0, {0, 0, 0}, 0},
#define HA_true_size 3

	{"layers", "List of layers to export or \"GUI\" for exporting what's visible on the GUI at the moment or empty for default export layer visibility",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_layers 4

	{"view", "If not empty, switch to view and compile before exporting",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_view 5

	{"colorspace", "Export in color or reduce colorspace",
	 RND_HATT_ENUM, 0, 0, {0, 0, 0}, colorspace_names}
#define HA_colorspace 6
};

#define NUM_OPTIONS (sizeof(svg_attribute_list)/sizeof(svg_attribute_list[0]))

static rnd_hid_attr_val_t svg_values[NUM_OPTIONS];

static char *out_filename;

static const rnd_export_opt_t *svg_get_export_options(rnd_hid_t *hid, int *n, rnd_design_t *dsg, void *appspec)
{
	const char *val = svg_values[HA_svgfile].str;

	if ((dsg != NULL) && ((val == NULL) || (*val == '\0')))
		csch_derive_default_filename(dsg, sch_rnd_export_appspec_prj(appspec), &svg_values[HA_svgfile], ".svg");

	if (n)
		*n = NUM_OPTIONS;
	return svg_attribute_list;
}

void svg_hid_export_to_file(rnd_design_t *hl, FILE * the_file, rnd_hid_attr_val_t * options, rnd_xform_t *xform)
{
	rnd_hid_expose_ctx_t ctx;

	ctx.design = hl;
	ctx.view.X1 = hl->dwg.X1;
	ctx.view.Y1 = hl->dwg.Y1;
	ctx.view.X2 = hl->dwg.X2;
	ctx.view.Y2 = hl->dwg.Y2;

	pctx->outf = the_file;

	TODO("set flip if needed");
	rnd_svg_background(pctx);

	xform->no_render_select = xform->no_render_hilight = !options[HA_screen_color].lng;

	rnd_app.expose_main(&svg_hid, &ctx, xform);
}

static int svg_do_export_sheet(rnd_hid_t *hid, rnd_design_t *dsg, rnd_hid_attr_val_t *options, sch_rnd_export_appspec_t *appspec, int *ovr)
{
	rnd_xform_t xform = {0};
	FILE *f = NULL;
	int do_close = 0;

	if (strcmp(options[HA_svgfile].str, "/dev/stdout") != 0) {
		out_filename = cschem_export_filename(dsg, options[HA_svgfile].str, NULL, appspec->fn_page_suffix, ".svg");

		f = rnd_fopen_askovr(dsg, out_filename, "wb", ovr);
		if (f == NULL) {
			int ern = errno;
			rnd_message(RND_MSG_ERROR, "svg_do_export(): failed to open %s: %s\n", out_filename, strerror(ern));
			free(out_filename);
			return -1;
		}
		free(out_filename);
		do_close = 1;
	}
	else
		f = stdout;

	rnd_svg_init(pctx, dsg, f, options[HA_opacity].lng, 1, options[HA_true_size].lng);
	if (f != NULL)
		rnd_svg_header(pctx);

	pctx->colorspace = options[HA_colorspace].lng;

	sch_rnd_set_export_layers(&xform, options[HA_layers].str);
	svg_hid_export_to_file(dsg, pctx->outf, options, &xform);

	if (pctx->outf != NULL) {
		rnd_svg_footer(pctx);
		if (do_close)
			fclose(pctx->outf);
	}
	pctx->outf = NULL;
	rnd_svg_uninit(pctx);

	return 0;
}


static void svg_do_export(rnd_hid_t *hid, rnd_design_t *design, rnd_hid_attr_val_t *options, void *appspec_)
{
	rnd_design_t *hl = design;
	csch_sheet_t *sheet = (csch_sheet_t *)hl;
	void *view_cookie;
	sch_rnd_export_appspec_t *appspec = (appspec_ == NULL) ? &sch_rnd_no_appspec : appspec_;

	pctx->comp_cnt = 0;

	if (!options) {
		svg_get_export_options(hid, 0, design, appspec);
		options = svg_values;
	}

	if (cschem_export_compile_pre((csch_project_t *)sheet->hidlib.project, options[HA_view].str, &view_cookie) != 0)
		return;

	sch_rnd_export_project_or_sheet(hid, design, options, appspec, svg_do_export_sheet);


	cschem_export_compile_post((csch_project_t *)sheet->hidlib.project, &view_cookie);
}

static int svg_parse_arguments(rnd_hid_t *hid, int *argc, char ***argv)
{
	rnd_export_register_opts2(hid, svg_attribute_list, sizeof(svg_attribute_list) / sizeof(svg_attribute_list[0]), svg_cookie, 0);
	return rnd_hid_parse_command_line(argc, argv);
}

static int svg_set_layer_group(rnd_hid_t *hid, rnd_design_t *design, rnd_layergrp_id_t group, const char *purpose, int purpi, rnd_layer_id_t layer, unsigned int flags, int is_empty, rnd_xform_t **xform)
{
	if (is_empty)
		return 0;

	{
		gds_t tmp_ln;
		const char *name;

		gds_init(&tmp_ln);
		TODO("do we need this at all? there's no multi-sheet svg export");
		name = "TODO:layer_name";
		rnd_svg_layer_group_begin(pctx, group, name, 0);
		gds_uninit(&tmp_ln);
	}
	return 1;
}

static void svg_set_drawing_mode(rnd_hid_t *hid, rnd_composite_op_t op, rnd_bool direct, const rnd_box_t *screen)
{
	rnd_svg_set_drawing_mode(pctx, hid, op, direct, screen);
}

static void svg_set_color(rnd_hid_gc_t gc, const rnd_color_t *color)
{
	rnd_svg_set_color(pctx, gc, color);
}

static void svg_draw_rect(rnd_hid_gc_t gc, rnd_coord_t x1, rnd_coord_t y1, rnd_coord_t x2, rnd_coord_t y2)
{
	rnd_svg_draw_rect(pctx, gc, x1, y1, x2, y2);
}

static void svg_fill_rect(rnd_hid_gc_t gc, rnd_coord_t x1, rnd_coord_t y1, rnd_coord_t x2, rnd_coord_t y2)
{
	rnd_svg_fill_rect(pctx, gc, x1, y1, x2, y2);
}

static void svg_draw_line(rnd_hid_gc_t gc, rnd_coord_t x1, rnd_coord_t y1, rnd_coord_t x2, rnd_coord_t y2)
{
	rnd_svg_draw_line(pctx, gc, x1, y1, x2, y2);
}

static void svg_draw_arc(rnd_hid_gc_t gc, rnd_coord_t cx, rnd_coord_t cy, rnd_coord_t width, rnd_coord_t height, rnd_angle_t start_angle, rnd_angle_t delta_angle)
{
	rnd_svg_draw_arc(pctx, gc, cx, cy, width, height, start_angle, delta_angle);
}

static void svg_fill_circle(rnd_hid_gc_t gc, rnd_coord_t cx, rnd_coord_t cy, rnd_coord_t radius)
{
	rnd_svg_fill_circle(pctx, gc, cx, cy, radius);
}

static void svg_fill_polygon_offs(rnd_hid_gc_t gc, int n_coords, rnd_coord_t *x, rnd_coord_t *y, rnd_coord_t dx, rnd_coord_t dy)
{
	rnd_svg_fill_polygon_offs(pctx, gc, n_coords, x, y, dx, dy);
}

static void svg_fill_polygon(rnd_hid_gc_t gc, int n_coords, rnd_coord_t *x, rnd_coord_t *y)
{
	rnd_svg_fill_polygon_offs(pctx, gc, n_coords, x, y, 0, 0);
}

static int svg_usage(rnd_hid_t *hid, const char *topic)
{
	fprintf(stderr, "\nsvg exporter command line arguments:\n\n");
	rnd_hid_usage(svg_attribute_list, sizeof(svg_attribute_list) / sizeof(svg_attribute_list[0]));
	fprintf(stderr, "\nUsage: sch-rnd [generic_options] -x svg [svg options] foo.rs\n\n");
	return 0;
}

int pplg_check_ver_export_svg(int ver_needed) { return 0; }

void pplg_uninit_export_svg(void)
{
	rnd_export_remove_opts_by_cookie(svg_cookie);
	rnd_hid_remove_hid(&svg_hid);
}

int pplg_init_export_svg(void)
{
	RND_API_CHK_VER;

	memset(&svg_hid, 0, sizeof(rnd_hid_t));

	rnd_hid_nogui_init(&svg_hid);

	svg_hid.struct_size = sizeof(rnd_hid_t);
	svg_hid.name = "svg";
	svg_hid.description = "Scalable Vector Graphics export";
	svg_hid.exporter = 1;

	svg_hid.get_export_options = svg_get_export_options;
	svg_hid.do_export = svg_do_export;
	svg_hid.parse_arguments = svg_parse_arguments;
	svg_hid.set_layer_group = svg_set_layer_group;
	svg_hid.make_gc = rnd_svg_make_gc;
	svg_hid.destroy_gc = rnd_svg_destroy_gc;
	svg_hid.set_drawing_mode = svg_set_drawing_mode;
	svg_hid.set_color = svg_set_color;
	svg_hid.set_line_cap = rnd_svg_set_line_cap;
	svg_hid.set_line_width = rnd_svg_set_line_width;
	svg_hid.set_draw_xor = rnd_svg_set_draw_xor;
	svg_hid.draw_line = svg_draw_line;
	svg_hid.draw_arc = svg_draw_arc;
	svg_hid.draw_rect = svg_draw_rect;
	svg_hid.fill_circle = svg_fill_circle;
	svg_hid.fill_polygon = svg_fill_polygon;
	svg_hid.fill_polygon_offs = svg_fill_polygon_offs;
	svg_hid.fill_rect = svg_fill_rect;
	svg_hid.set_crosshair = rnd_svg_set_crosshair;
	svg_hid.argument_array = svg_values;

	svg_hid.usage = svg_usage;

	rnd_hid_register_hid(&svg_hid);
	rnd_hid_load_defaults(&svg_hid, svg_attribute_list, NUM_OPTIONS);

	return 0;
}
