/*
 *                            COPYRIGHT
 *
 *  camv-rnd - electronics-related CAM viewer - web2 export (html+svg+js)
 *  Copyright (C) 2022,2024 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/pcb-rnd
 *    lead developer: http://repo.hu/projects/pcb-rnd/contact.html
 *    mailing list: pcb-rnd (at) list.repo.hu (send "subscribe")
 */

/* Based on the svg exporter */

#include "config.h"
#include "conf_core.h"

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.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 "data.h"
#include "draw.h"
#include "export.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_web2.h>

static rnd_hid_t web2_hid;

const char *web2_cookie = "web2 HID";

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

/* %start-doc options "93 SVG Options"
@ftable @code
@cindex flip
@item --flip
Flip board, look at it from the bottom side
@end ftable
%end-doc
*/
	{"flip", "Flip board",
	 RND_HATT_BOOL, 0, 0, {0, 0, 0}, 0},
#define HA_flip 2

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

/* %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 4
};

#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)
{
	if (n)
		*n = NUM_OPTIONS;
	return web2_attribute_list;
}

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;
	camv_design_t *camv = (camv_design_t *)dsg;

	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;

	if (options[HA_flip].lng) {
		rnd_conf_toggle_heditor_("view/flip_y", view.flip_y);
		camv_data_reverse_layers(camv, 0);
	}

	rnd_web2_background(pctx);

	xform->announce_layers = 1;

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


	/* camv-rnd always emits a single page as boards are single-page by definition */
	rnd_web2_print_page_pre(pctx, "camv-rnd export");
	rnd_app.expose_main(&web2_hid, &ctx, xform);
	rnd_web2_print_page_post(pctx);


	/* restore */
	if (options[HA_flip].lng) {
		rnd_conf_toggle_heditor_("view/flip_y", view.flip_y);
		camv_data_reverse_layers(camv, 0);
	}
}

static void web2_do_export(rnd_hid_t *hid, rnd_design_t *design, rnd_hid_attr_val_t *options, void *appspec)
{
	rnd_xform_t xform;
	const char *fn;
	FILE *f = NULL;

	pctx->svg.comp_cnt = 0;

	if (!options) {
		web2_get_export_options(hid, 0, design, appspec);
		options = web2_values;
	}

	rnd_web2_init(pctx, design, f, options[HA_template].str);
	pctx->svg.opacity = options[HA_opacity].lng;
	pctx->svg.flip = options[HA_flip].lng;
	pctx->svg.true_size = 0;


	fn = camv_export_filename(design, options[HA_web2file].str, ".html");
	f = rnd_fopen_askovr(design, fn, "wb", NULL);
	if (f == NULL) {
		int ern = errno;
		rnd_message(RND_MSG_ERROR, "web2_do_export(): failed to open %s: %s\n", fn, strerror(ern));
		perror(fn);
		return;
	}

	if (rnd_web2_new_file(pctx, f, fn) != 0)
		return;

	pctx->svg.outf = f;

	if (f != NULL)
		rnd_web2_print_header(pctx);

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

	web2_hid_export_to_file(design, pctx->outf, options, &xform);

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

	rnd_web2_uninit(pctx);
}

static int web2_parse_arguments(rnd_hid_t *hid, int *argc, char ***argv)
{
	rnd_app.multi_design = 1; /* permit loading multiple files */
	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)
{
	gds_t tmp_ln;
	const char *si;

	if (is_empty)
		return 0;

	gds_init(&tmp_ln);

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

	rnd_web2_layer_group_begin(pctx, group, tmp_ln.array, 0);

	gds_uninit(&tmp_ln);

	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;
}
