/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - web2 (html+svg+js) export
 *  Copyright (C) 2026 Tibor 'Igor2' Palinkas
 *
 *  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., 31 Milk Street, # 960789 Boston, MA 02196 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 <ctype.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 <librnd/plugins/lib_exp_text/draw_web2.h>

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

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



static rnd_hid_t web2_hid;

const char *web2_cookie = "export_web2";

static rnd_web2_t pctx_, *pctx = &pctx_;

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

static const rnd_export_opt_t web2_attribute_list[] = {
	/* other HIDs expect this to be first.  */

/* %start-doc options "93 SVG Options"
@ftable @code
@item --outfile <string>
Name of the file to be exported to. Can contain a path.
@end ftable
%end-doc
*/
	{"outfile", "Graphics output file",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_web2file 0

/* %start-doc options "93 SVG Options"
@ftable @code
@cindex opacity
@item --opacity
Layer opacity
@end ftable
%end-doc
*/
	{"opacity", "Layer opacity in percentage (integer, 0..100)",
	 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

	{"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 3

/* %start-doc options "91 web2 Export"
@ftable @code
@cindex multi-file
@item --multi-file
Produce multiple files, one per page, instead of a single multi page file.
@end ftable
%end-doc
*/
	{"multi-file", "Produce multiple files, one per page, instead of a single file",
	 RND_HATT_BOOL, 0, 0, {0, 0, 0}, 0},
#define HA_multifile 4

/* %start-doc options "93 web2 Options"
@ftable @code
@item --template <string>
Name of the lihata template file to be used instead of the default web2 template. Can contain a path.
@end ftable
%end-doc
*/
	{"template", "web2 template (lihata file)",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_template 5

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

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

};

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

static rnd_hid_attr_val_t web2_values[NUM_OPTIONS];

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

	if ((dsg != NULL) && ((val == NULL) || (*val == '\0')))
		csch_derive_default_filename(dsg, sch_rnd_export_appspec_prj(appspec), &web2_values[HA_web2file], ".html");

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

static void web2_gen_search(rnd_design_t *dsg)
{
	htip_entry_t *e;
	csch_sheet_t *sheet = (csch_sheet_t *)dsg;
	static const rnd_coord_t boarder = RND_MM_TO_COORD(2);

	/* add symbols by name */
	for(e = htip_first(&sheet->direct.id2obj); e != NULL; e = htip_next(&sheet->direct.id2obj, e)) {
		csch_cgrp_t *sym = e->value;
		const char *name;

		if (sym->role != CSCH_ROLE_SYMBOL) continue;
		name = csch_attrib_get_str(&sym->attr, "name");
		if (name == NULL) continue;

			rnd_web2_search_append(pctx, name,
				C2P(sym->hdr.bbox.x1) - boarder, dsg->dwg.Y2 - C2P(sym->hdr.bbox.y2) - boarder, C2P(sym->hdr.bbox.x2) + boarder, dsg->dwg.Y2 - C2P(sym->hdr.bbox.y1) + boarder);
	}
}

static void web2_hid_export_to_file(rnd_design_t *dsg, FILE *the_file, rnd_hid_attr_val_t * options, rnd_xform_t *xform)
{
	rnd_hid_expose_ctx_t ctx;

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

	pctx->outf = the_file;

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

	rnd_web2_background(pctx);

	rnd_web2_layer_group_map(pctx, 1);
	rnd_app.expose_main(&web2_hid, &ctx, xform);
	rnd_web2_layer_group_map(pctx, 0);


	/* pcb-rnd always emits a single page as boards are single-page by definition */
	rnd_web2_print_page_pre(pctx, rnd_hid_export_fn(pctx->hidlib->loadname));
	rnd_app.expose_main(&web2_hid, &ctx, xform);
	web2_gen_search(dsg);
	rnd_web2_print_page_post(pctx);

	rnd_conf_update(NULL, -1); /* restore forced sets */
}

static int web2_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};
	int do_close = 0;


	if ((pctx->outf == NULL) || options[HA_multifile].lng) {
		FILE *f;
		char *out_filename;
		const char *suff = (options[HA_multifile].lng) ? appspec->fn_page_suffix : NULL;

		out_filename = cschem_export_filename(dsg, options[HA_web2file].str, NULL, suff, ".web2");
		f = rnd_fopen_askovr(dsg, out_filename, "wb", ovr);

		if (options[HA_multifile].lng)
			do_close = 1;
		if (f == NULL) {
			int ern = errno;
			rnd_message(RND_MSG_ERROR, "web2_do_export(): failed to open %s: %s\n", out_filename, strerror(ern));
			free(out_filename);
			return -1;
		}
		free(out_filename);

		rnd_web2_init(pctx, dsg, f, options[HA_template].str);

		pctx->svg.opacity = options[HA_opacity].lng;
		pctx->svg.colorspace = options[HA_colorspace].lng;
		pctx->svg.flip = 1;

		if (pctx->outf != NULL)
			rnd_web2_print_header(pctx);
	}



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

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

	return 0;
}

static void web2_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->svg.comp_cnt = 0;
	if (!options) {
		web2_get_export_options(hid, 0, design, appspec);
		options = web2_values;
	}

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


	if (pctx->outf != NULL)
		rnd_web2_print_header(pctx);

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

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

	if (pctx->outf != NULL)
		rnd_web2_print_footer(pctx);

	rnd_web2_uninit(pctx);
}

static int web2_parse_arguments(rnd_hid_t *hid, int *argc, char ***argv)
{
	rnd_export_register_opts2(hid, web2_attribute_list, sizeof(web2_attribute_list) / sizeof(web2_attribute_list[0]), web2_cookie, 0);
	return rnd_hid_parse_command_line(argc, argv);
}

static int web2_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)
{
	const char *si;
	char *so, *end, tmp[128];
	if (is_empty)
		return 0;

	/* filter names so they comform the ID syntax the js expects */
	end = tmp+sizeof(tmp)-1;
	for(si = purpose, so = tmp; (*si != '\0') && (so < end); si++) {
		if (!isalnum(*si)) {
			if ((so > tmp) && (so[-1] != '_')) {
				*so = '_';
				so++;
			}
		}
		else {
			*so = *si;
			so++;
		}
	}
	*so = '\0';

	rnd_web2_layer_group_begin(pctx, group, tmp, 0);

	return 1;
}

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

static void web2_set_color(rnd_hid_gc_t gc, const rnd_color_t *color)
{
	rnd_web2_set_color(pctx, gc, color);
}

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

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

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

static void web2_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_web2_draw_arc(pctx, gc, cx, cy, width, height, start_angle, delta_angle);
}

static void web2_fill_circle(rnd_hid_gc_t gc, rnd_coord_t cx, rnd_coord_t cy, rnd_coord_t radius)
{
	rnd_web2_fill_circle(pctx, gc, cx, cy, radius);
}

static void web2_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_web2_fill_polygon_offs(pctx, gc, n_coords, x, y, dx, dy);
}

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

static int web2_usage(rnd_hid_t *hid, const char *topic)
{
	fprintf(stderr, "\nweb2 exporter command line arguments:\n\n");
	rnd_hid_usage(web2_attribute_list, sizeof(web2_attribute_list) / sizeof(web2_attribute_list[0]));
	fprintf(stderr, "\nUsage: pcb-rnd [generic_options] -x web2 [web2 options] foo.pcb\n\n");
	return 0;
}

int pplg_check_ver_export_web2(int ver_needed) { return 0; }

void pplg_uninit_export_web2(void)
{
	rnd_export_remove_opts_by_cookie(web2_cookie);
	rnd_hid_remove_hid(&web2_hid);
}

int pplg_init_export_web2(void)
{
	RND_API_CHK_VER;

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

	rnd_hid_nogui_init(&web2_hid);

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

	web2_hid.get_export_options = web2_get_export_options;
	web2_hid.do_export = web2_do_export;
	web2_hid.parse_arguments = web2_parse_arguments;
	web2_hid.set_layer_group = web2_set_layer_group;
	web2_hid.make_gc = rnd_web2_make_gc;
	web2_hid.destroy_gc = rnd_web2_destroy_gc;
	web2_hid.set_drawing_mode = web2_set_drawing_mode;
	web2_hid.set_color = web2_set_color;
	web2_hid.set_line_cap = rnd_web2_set_line_cap;
	web2_hid.set_line_width = rnd_web2_set_line_width;
	web2_hid.set_draw_xor = rnd_web2_set_draw_xor;
	web2_hid.draw_line = web2_draw_line;
	web2_hid.draw_arc = web2_draw_arc;
	web2_hid.draw_rect = web2_draw_rect;
	web2_hid.fill_circle = web2_fill_circle;
	web2_hid.fill_polygon = web2_fill_polygon;
	web2_hid.fill_polygon_offs = web2_fill_polygon_offs;
	web2_hid.fill_rect = web2_fill_rect;
	web2_hid.set_crosshair = rnd_web2_set_crosshair;
	web2_hid.argument_array = web2_values;

	web2_hid.usage = web2_usage;

	rnd_hid_register_hid(&web2_hid);
	rnd_hid_load_defaults(&web2_hid, web2_attribute_list, NUM_OPTIONS);

	return 0;
}
