/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - Accel netlist export
 *  Copyright (C) 2025 Tibor 'Igor2' Palinkas
 *  Copyright (C) 2025 Aron Barath
 *
 *  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 <stdio.h>
#include <string.h>
#include <ctype.h>
#include <librnd/core/compat_misc.h>
#include <librnd/core/safe_fs.h>
#include <librnd/core/plugins.h>
#include <librnd/core/error.h>
#include <libcschem/config.h>
#include <libcschem/plug_io.h>

#include <plugins/lib_netlist_exp/lib_netlist_exp.h>

static csch_plug_io_t eaccel_net, eaccel_naked_net;

static int accel_export_prio_hdr(const char *fn, const char *fmt, csch_plug_io_type_t type)
{
	if (type != CSCH_IOTYP_NETLIST)
		return 0;

	if (strstr(fmt, "accel") != NULL) {
		if (strstr(fmt, "without") == NULL)
			return 100;
		return 70;
	}

	return 0;
}

static int accel_export_prio_naked(const char *fn, const char *fmt, csch_plug_io_type_t type)
{
	if (type != CSCH_IOTYP_NETLIST)
		return 0;

	if (strstr(fmt, "accel") != NULL) {
		if (strstr(fmt, "without") != NULL)
			return 100;
		return 0; /* do the no-header variant only when explicitly requested; plain accel without any hint on the header does the hdr version */
	}

	return 0;
}

static void accel_print_filename(FILE* const f, const char* fn)
{
	while(*fn)
	{
		char ch = *fn++;

		if(ch=='\"')
		{
			ch = '_';
		}

		fputc(ch, f);
	}
}

static void accel_print_value(FILE* const f, const char* str)
{
	const char* p;

	if(!str)
	{
		return;
	}

	p = strchr(str, '\"');

	if(p)
	{
		rnd_message(RND_MSG_ERROR, "accel: Broken output! Value contains quote sym (\"), it is replaced with apos (\'): \"%s\"\n", str);

		while(p)
		{
			fwrite(str, p-str, 1, f);

			while((*p)=='\"')
			{
				fputc('\'', f);
				++p;
			}

			str = p;

			p = strchr(str, '\"');
		}
	}

	fputs(str, f);
}

/* Export abstract components; exports refdes, footprint, value and device. */
/* Format does not support custom tags */
static void accel_export_comps(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;
	for(e = htsp_first(&abs->comps); e != NULL; e = htsp_next(&abs->comps, e)) {
		csch_acomp_t *comp = e->value;
		const char *refdes = sch_nle_get_refdes(comp);
		const char *fp, *dev, *val;

		if (refdes == NULL)
			continue;

		if (comp->hdr.omit)
			continue;

		/* Get main symbol attributes the safe way, considering alternate names;
		   these should be always exported and are usually hardwired in the
		   netlist format. */
		fp = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_FOOTPRINT);
		val = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_VALUE);
		dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_DEVICE);

		fprintf(f, "  (compInst \"");
		accel_print_value(f, refdes);
		fprintf(f, "\"\r\n");

		fprintf(f, "    (compRef \"");
		accel_print_value(f, dev);
		fprintf(f, "\")\r\n");

		fprintf(f, "    (originalName \"");
		accel_print_value(f, fp);
		fprintf(f, "\")\r\n");

		fprintf(f, "    (compValue \"");
		accel_print_value(f, val);
		fprintf(f, "\")\r\n");

		fprintf(f, "  )\r\n");
	}
}

/* Export abstract nets; exports net's name and a list of refdes-pinnum */
/* pairs connected; format does not support custom attrs */
static void accel_export_nets(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;
	long n;

	for(e = htsp_first(&abs->nets); e != NULL; e = htsp_next(&abs->nets, e)) {
		csch_anet_t *net = e->value;
		const char *netname = sch_nle_get_netname(net);
		int net_exported = 0; /* net had at least one connection so it was written */

		if (net->hdr.omit) continue;

		for(n = 0; n < net->conns.used; n++) {
			csch_aport_t *port = net->conns.array[n];
			const char *refdes = NULL, *pinnums;

			if (port->hdr.type != CSCH_ATYPE_PORT) {
				rnd_message(RND_MSG_ERROR, "accel: invalid connection (object type)\n");
				continue;
			}

			pinnums = sch_nle_get_pinnum(port);
			if (pinnums == NULL) {
				rnd_message(RND_MSG_ERROR, "accel: can't determine port's pin number\n");
				continue;
			}

			if (port->parent != NULL) {
				refdes = sch_nle_get_refdes(port->parent);
				if (port->parent->hdr.omit)
					continue; /* omit component */
			}
			if (refdes == NULL) {
				/* This is not an error: no refdes means: do not export (e.g. gnd) */
/*				rnd_message(RND_MSG_ERROR, "accel: can't determine port's parent component refdes\n");*/
				continue;
			}

			/* split up pinnum at space and create one or more conn lines connecting
			   each pin to the given net */
			SCH_NLE_FOREACH_PINNUM(pinnums, my_num,
				{
					if(!net_exported)
					{
						fprintf(f, "  (net \"");
						accel_print_value(f, netname);
						fprintf(f, "\"\r\n");
						net_exported = 1;
					}

					fprintf(f, "    (node \"");
					accel_print_value(f, refdes);
					fprintf(f, "\" \"");
					accel_print_value(f, my_num);
					fprintf(f, "\")\r\n");
				}
			);
		}

		/* If the net got exported, close the "net" block */
		if(net_exported)
		{
			fprintf(f, "  )\r\n");
		}
	}
}


/* Export netlist from the abstract model */
static int accel_export_project_abst(const char *fn, const char *fmt, csch_abstract_t *abs, rnd_hid_attr_val_t *options, int with_header)
{
	TODO("get hidlib as an arg")
	rnd_design_t *hidlib = NULL;
	FILE *f = rnd_fopen(hidlib, fn, "w");
	if (f == NULL)
		return -1;

	if(with_header)
	{
		fprintf(f, "ACCEL_ASCII \"");
		accel_print_filename(f, fn);
		fprintf(f, "\"\r\n");

		fprintf(f, "\r\n");

		fprintf(f, "(asciiHeader\r\n");
		fprintf(f, "  (asciiVersion 2 2)\r\n");
		fprintf(f, "  (timeStamp 2025 9 4 10 0 6)\r\n");
		fprintf(f, "  (fileAuthor \"\")\r\n");
		fprintf(f, "  (copyright \"\")\r\n");
		fprintf(f, "  (program \"sch-rnd\" \"\")\r\n");
		fprintf(f, "  (headerString \"Created by sch-rnd\")\r\n");
		fprintf(f, "  (fileUnits Mil)\r\n");
		fprintf(f, ")\r\n");
		fprintf(f, "\r\n");
	}

	fprintf(f, "(netlist \"");
	accel_print_filename(f, fn);
	fprintf(f, "\"\r\n");

	accel_export_comps(f, abs);
	accel_export_nets(f, abs);

	fprintf(f, ")\r\n");
	fclose(f);
	return 0;
}

static int accel_export_project_abst_hdr(const char *fn, const char *fmt, csch_abstract_t *abs, rnd_hid_attr_val_t *options)
{
	return accel_export_project_abst(fn, fmt, abs, options, 1);
}

static int accel_export_project_abst_naked(const char *fn, const char *fmt, csch_abstract_t *abs, rnd_hid_attr_val_t *options)
{
	return accel_export_project_abst(fn, fmt, abs, options, 0);
}

#include "hid_impl.c"

int pplg_check_ver_export_accel(int ver_needed) { return 0; }

void pplg_uninit_export_accel(void)
{
	csch_plug_io_unregister(&eaccel_net);
	rnd_export_remove_opts_by_cookie(accel_cookie);
	rnd_hid_remove_hid(&accel_hid);
}

int pplg_init_export_accel(void)
{
	RND_API_CHK_VER;

	eaccel_net.name = "export to Accel (with headers)";
	eaccel_net.export_prio = accel_export_prio_hdr;
	eaccel_net.export_project_abst = accel_export_project_abst_hdr;
	eaccel_net.ext_export_project = ".net";
	csch_plug_io_register(&eaccel_net);

	eaccel_naked_net.name = "export to Accel (without headers)";
	eaccel_naked_net.export_prio = accel_export_prio_naked;
	eaccel_naked_net.export_project_abst = accel_export_project_abst_naked;
	eaccel_naked_net.ext_export_project = ".net";
	csch_plug_io_register(&eaccel_naked_net);

	rnd_hid_nogui_init(&accel_hid);

	accel_hid.struct_size = sizeof(rnd_hid_t);
	accel_hid.name = "accel";
	accel_hid.description = "Exports project's Accel netlist, with headers";
	accel_hid.exporter = 1;

	accel_hid.get_export_options = accel_get_export_options;
	accel_hid.do_export = accel_do_export_hdr;
	accel_hid.parse_arguments = accel_parse_arguments;
	accel_hid.argument_array = accel_values;

	accel_hid.usage = accel_usage;

	rnd_hid_register_hid(&accel_hid);
	rnd_hid_load_defaults(&accel_hid, accel_options, NUM_OPTIONS);


	rnd_hid_nogui_init(&accel_naked_hid);

	accel_naked_hid.struct_size = sizeof(rnd_hid_t);
	accel_naked_hid.name = "accel_naked";
	accel_naked_hid.description = "Exports project's Accel netlist, without headers";
	accel_naked_hid.exporter = 1;

	accel_naked_hid.get_export_options = accel_get_export_options;
	accel_naked_hid.do_export = accel_do_export_naked;
	accel_naked_hid.parse_arguments = accel_parse_arguments;
	accel_naked_hid.argument_array = accel_values;

	accel_naked_hid.usage = accel_usage;

	rnd_hid_register_hid(&accel_naked_hid);
	rnd_hid_load_defaults(&accel_naked_hid, accel_options, NUM_OPTIONS);

	return 0;
}

