/*
   This file is part of pcb-rnd and was part of gEDA/PCB but lacked proper
   copyright banner at the fork. It probably has the same copyright as
   gEDA/PCB as a whole in 2011.
*/

#include <libcschem/config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <librnd/core/math_helper.h>
#include <librnd/core/color.h>
#include <librnd/core/rnd_printf.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/core/compat_misc.h>
#include <librnd/plugins/lib_exp_text/draw_eps.h>

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

#include "export_ps.h"


static rnd_hid_t eps_hid;

static rnd_eps_t pctx_, *pctx = &pctx_;

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

/* %start-doc options "92 Encapsulated Postscript Export"
@ftable @code
@item --eps-file <string>
Name of the encapsulated postscript output file. Can contain a path.
@end ftable
%end-doc
*/
	{"eps-file", "Encapsulated Postscript output file",
	 RND_HATT_STRING, 0, 0, {0, 0, 0}, 0},
#define HA_psfile 0

/* %start-doc options "92 Encapsulated Postscript Export"
@ftable @code
@item --eps-scale <num>
Scale EPS output by the parameter @samp{num}.
@end ftable
%end-doc
*/
	{"eps-scale", "EPS scale",
	 RND_HATT_REAL, 0, 100, {0, 0, 1.0}, 0},
#define HA_scale 1

/* %start-doc options "92 Encapsulated Postscript Export"
@ftable @code
@item --monochrome
Convert output to monochrome.
@end ftable
%end-doc
*/
	{"monochrome", "Convert to monochrome",
	 RND_HATT_BOOL, 0, 0, {0, 0, 0}, 0},
#define HA_mono 2

	{"fill-gray-threshold", "In monochrome, fill polygons with gray if color is lighter than this percentage (0 is black, 100 is white)",
	 RND_HATT_INTEGER, 0, 100, {80, 0, 0}, 0},
#define HA_fill_gray_threshold 3

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

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

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

static rnd_hid_attr_val_t eps_values[NUM_OPTIONS];

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

	if ((dsg != NULL) && ((val == NULL) || (*val == '\0')))
		csch_derive_default_filename(dsg, sch_rnd_export_appspec_prj(appspec), &eps_values[HA_psfile], ".eps");

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

static const char *filename;
static double eps_fill_gray_thrs;
static rnd_hid_attr_val_t *options_;

void eps_hid_export_to_file(rnd_design_t *hl, FILE * the_file, rnd_hid_attr_val_t *options, rnd_xform_t *xform)
{
	rnd_box_t region, *bnds;
	double dtmp;
	rnd_hid_expose_ctx_t ctx;

	options_ = options;

	region.X1 = hl->dwg.X1;
	region.Y1 = hl->dwg.Y1;
	region.X2 = hl->dwg.X2;
	region.Y2 = hl->dwg.Y2;
	bnds = &region;

	rnd_eps_init(pctx, the_file, *bnds, options_[HA_scale].dbl, options[HA_mono].lng, 0);

	dtmp = (double)options[HA_fill_gray_threshold].lng / 100.0;
	eps_fill_gray_thrs = dtmp * dtmp * 3;

	if (pctx->outf != NULL)
		rnd_eps_print_header(pctx, rnd_hid_export_fn(filename), 0, 1);

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

	ctx.design = hl;
	ctx.view = *bnds;
	rnd_app.expose_main(&eps_hid, &ctx, xform);

	rnd_eps_print_footer(pctx);

	options_ = NULL;
}

static int eps_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};

	filename = cschem_export_filename(dsg, options[HA_psfile].str, NULL, appspec->fn_page_suffix, ".eps");
	pctx->outf = rnd_fopen_askovr(dsg, filename, "w", ovr);
	if (pctx->outf == NULL) {
		perror(filename);
		return -1;
	}

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

	fclose(pctx->outf);
	return 0;
}

static void eps_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_;

	if (!options) {
		eps_get_export_options(hid, 0, design, appspec);
		options = eps_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, eps_do_export_sheet);

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

static int eps_parse_arguments(rnd_hid_t *hid, int *argc, char ***argv)
{
	rnd_export_register_opts2(hid, eps_attribute_list, sizeof(eps_attribute_list) / sizeof(eps_attribute_list[0]), ps_cookie, 0);
	return rnd_hid_parse_command_line(argc, argv);
}

static int eps_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)
{
	return 1;
}

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

static rnd_color_t eps_last_color;
static void eps_set_color(rnd_hid_gc_t gc, const rnd_color_t *color)
{
	eps_last_color = *color;
	rnd_eps_set_color(pctx, gc, color);
}

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

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

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

static void eps_fill_circle(rnd_hid_gc_t gc, rnd_coord_t cx, rnd_coord_t cy, rnd_coord_t radius)
{
	rnd_eps_fill_circle(pctx, gc, cx, cy, radius);
}

static void eps_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)
{
	/* maybe tweak fill color so that light fills remain light grey */
	if (pctx->in_mono) {
		double intens2 = eps_last_color.fr * eps_last_color.fr + eps_last_color.fg * eps_last_color.fg + eps_last_color.fb * eps_last_color.fb;

		if (intens2 >= eps_fill_gray_thrs) {
			rnd_color_t clr = eps_last_color;
			int avg = rnd_round((double)(clr.r + clr.g + clr.b) / 3.0);
			clr.r = clr.g = clr.b = avg;

			pctx->in_mono = 0;
			rnd_eps_set_color(pctx, gc, &clr);
			pctx->in_mono = 1;
		}
	}

	rnd_eps_fill_polygon_offs(pctx, gc, n_coords, x, y, dx, dy);
}

static void eps_fill_polygon(rnd_hid_gc_t gc, int n_coords, rnd_coord_t *x, rnd_coord_t *y)
{
	eps_fill_polygon_offs(gc, n_coords, x, y, 0, 0);
}

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

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

void hid_eps_uninit()
{
	rnd_hid_remove_hid(&eps_hid);
}

void hid_eps_init()
{
	memset(&eps_hid, 0, sizeof(rnd_hid_t));

	rnd_hid_nogui_init(&eps_hid);

	eps_hid.struct_size = sizeof(rnd_hid_t);
	eps_hid.name = "eps";
	eps_hid.description = "Encapsulated Postscript";
	eps_hid.exporter = 1;

	eps_hid.get_export_options = eps_get_export_options;
	eps_hid.do_export = eps_do_export;
	eps_hid.parse_arguments = eps_parse_arguments;
	eps_hid.set_layer_group = eps_set_layer_group;
	eps_hid.make_gc = rnd_eps_make_gc;
	eps_hid.destroy_gc = rnd_eps_destroy_gc;
	eps_hid.set_drawing_mode = eps_set_drawing_mode;
	eps_hid.set_color = eps_set_color;
	eps_hid.set_line_cap = rnd_eps_set_line_cap;
	eps_hid.set_line_width = rnd_eps_set_line_width;
	eps_hid.set_draw_xor = rnd_eps_set_draw_xor;
	eps_hid.draw_line = eps_draw_line;
	eps_hid.draw_arc = eps_draw_arc;
	eps_hid.draw_rect = eps_draw_rect;
	eps_hid.fill_circle = eps_fill_circle;
	eps_hid.fill_polygon = eps_fill_polygon;
	eps_hid.fill_polygon_offs = eps_fill_polygon_offs;
	eps_hid.fill_rect = eps_fill_rect;
	eps_hid.set_crosshair = rnd_eps_set_crosshair;
	eps_hid.argument_array = eps_values;

	eps_hid.usage = eps_usage;

	rnd_hid_register_hid(&eps_hid);
	rnd_hid_load_defaults(&eps_hid, eps_attribute_list, NUM_OPTIONS);
}
