/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - Eagle5 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 eeagle5_net;
static const char* eagle5_get_outparts_option(rnd_hid_attr_val_t* options);

static int eagle5_export_prio(const char *fn, const char *fmt, csch_plug_io_type_t type)
{
	if (type != CSCH_IOTYP_NETLIST)
		return 0;
	if (rnd_strcasecmp(fmt, "eagle5") == 0)
		return 100;
	return 0;
}

static void eagle5_assert_value(const char* str, const int maxlen)
{
	if(strchr(str, ' '))
	{
		rnd_message(RND_MSG_ERROR, "eagle5: Broken output! Name contains space, but it cannot be escaped: %s\n", str);
	}
}

/* Export abstract components; exports refdes, footprint, value and device */
static void eagle5_export_comps(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;

	const int w_part = 8;
	const int w_val  = 14;
	const int w_dev  = 17;
	const int w_pkg  = 8;

	fprintf(f, "Exported from sch-rnd at 09-29-2025 14:13:00\n");
	fprintf(f, "\n");
	fprintf(f, "EAGLE Version 5.11.0 Copyright (c) 1988-2010 CadSoft\n");
	fprintf(f, "\n");
	fprintf(f, "%-*s %-*s %-*s %-*s Library Sheet\n", w_part, "Part",
		w_val, "Value", w_dev, "Device", w_pkg, "Package");
	fprintf(f, "\n");

	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 hardwiared 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);

		if(!fp)
		{
			fp = "~";
		}

		if(!val)
		{
			val = "~";
		}

		if(!dev)
		{
			dev = "~";
		}

		eagle5_assert_value(refdes, w_part);
		eagle5_assert_value(fp, w_pkg);
		eagle5_assert_value(val, w_val);
		eagle5_assert_value(dev, w_dev);

		fprintf(f, "%-*s %-*s %-*s %-*s sch-rnd 1\n", w_part, refdes,
			w_val, val, w_dev, dev, w_pkg, fp);
	}
}

/* Export abstract nets; exports net's name, a list of refdes-pinnum pairs */
/* connected, and pin names */
static void eagle5_export_nets(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e;
	long n;

	const int w_net  = 8;
	const int w_part = 8;
	const int w_pad  = 8;
	const int w_pin  = 10;

	fprintf(f, "Netlist\n");
	fprintf(f, "\n");
	fprintf(f, "Exported from sch-rnd at 09-29-2025 14:13:00\n");
	fprintf(f, "\n");
	fprintf(f, "EAGLE Version 5.11.0 Copyright (c) 1988-2010 CadSoft\n");
	fprintf(f, "\n");
	fprintf(f, "%-*s %-*s %-*s %-*s Sheet\n", w_net, "Net", w_part, "Part",
		w_pad, "Pad", w_pin, "Pin");
	fprintf(f, "\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 *pinname = sch_nle_get_alt_attr(&port->hdr.attr, SCH_NLE_ALTATTR_PINNAME);
			const char *refdes = NULL, *pinnums;

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

			pinnums = sch_nle_get_pinnum(port);
			if (pinnums == NULL) {
				rnd_message(RND_MSG_ERROR, "eagle5: 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, "eagle5: can't determine port's parent component refdes\n");*/
				continue;
			}

			eagle5_assert_value(netname, w_net);

			if(pinname)
			{
				eagle5_assert_value(pinname, w_pin);
			}

			/* 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,
				{
					eagle5_assert_value(refdes, w_part);
					eagle5_assert_value(my_num, w_pad);

					fprintf(f, "%-*s %-*s %-*s %-*s 1\n",
						w_net, (net_exported ? "" : netname),
						w_part, refdes,
						w_pad, my_num,
						w_pin, pinname ? pinname : my_num);

					net_exported = 1;
				}
			);
		}

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

#define EAGLE5_NET_EXT   ".net"
#define EAGLE5_PARTS_EXT ".parts"

static FILE* eagle5_open_parts(rnd_design_t* hidlib, const char* outparts,
	const char* netfn)
{
	if(outparts)
	{
		return rnd_fopen(hidlib, outparts, "w");
	}
	else
	{
		const size_t len = strlen(netfn);
		char* const buf = (char*)malloc(len+sizeof(EAGLE5_PARTS_EXT));

		if(buf)
		{
			FILE* f;
			char* p = buf + len - (sizeof(EAGLE5_NET_EXT)-1);

			strcpy(buf, netfn);

			if(len>(sizeof(EAGLE5_NET_EXT)-1) && strcmp(p, EAGLE5_NET_EXT)==0)
			{
				strcpy(p, EAGLE5_PARTS_EXT);
			}
			else
			{
				strcat(p, EAGLE5_PARTS_EXT);
			}

			f = rnd_fopen(hidlib, buf, "w");

			free(buf);

			return f;
		}
	}

	return NULL;
}

/* Export netlist from the abstract model */
static int eagle5_export_project_abst(const char *fn, const char *fmt, csch_abstract_t *abs, rnd_hid_attr_val_t *options)
{
	TODO("get hidlib as an arg")
	rnd_design_t *hidlib = NULL;
	FILE* f_parts;
	FILE* f_net = rnd_fopen(hidlib, fn, "w");

	if(f_net == NULL)
		return -1;

	f_parts = eagle5_open_parts(hidlib, eagle5_get_outparts_option(options), fn);
	if(f_parts == NULL)
	{
		fclose(f_net);
		return -1;
	}

	eagle5_export_nets(f_net, abs);
	eagle5_export_comps(f_parts, abs);

	fclose(f_net);
	fclose(f_parts);
	return 0;
}

#include "hid_impl.c"

static const char* eagle5_get_outparts_option(rnd_hid_attr_val_t* options)
{
	return options[HA_outparts].str;
}

int pplg_check_ver_export_eagle5(int ver_needed) { return 0; }

void pplg_uninit_export_eagle5(void)
{
	csch_plug_io_unregister(&eeagle5_net);
	rnd_export_remove_opts_by_cookie(eagle5_cookie);
	rnd_hid_remove_hid(&eagle5_hid);
}

int pplg_init_export_eagle5(void)
{
	RND_API_CHK_VER;

	eeagle5_net.name = "export to Eagle5";
	eeagle5_net.export_prio = eagle5_export_prio;
	eeagle5_net.export_project_abst = eagle5_export_project_abst;
	eeagle5_net.ext_export_project = ".net";
	csch_plug_io_register(&eeagle5_net);


	rnd_hid_nogui_init(&eagle5_hid);

	eagle5_hid.struct_size = sizeof(rnd_hid_t);
	eagle5_hid.name = "eagle5";
	eagle5_hid.description = "Exports project's Eagle5 netlist";
	eagle5_hid.exporter = 1;

	eagle5_hid.get_export_options = eagle5_get_export_options;
	eagle5_hid.do_export = eagle5_do_export;
	eagle5_hid.parse_arguments = eagle5_parse_arguments;
	eagle5_hid.argument_array = eagle5_values;

	eagle5_hid.usage = eagle5_usage;

	rnd_hid_register_hid(&eagle5_hid);
	rnd_hid_load_defaults(&eagle5_hid, eagle5_options, NUM_OPTIONS);


	return 0;
}

