/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - Orcad 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 eorcad_net;

static int orcad_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, "orcad") == 0)
		return 100;
	return 0;
}

static void orcad_print_value(FILE* const f, const char* str)
{
	if(strchr(str, ' '))
	{
		rnd_message(RND_MSG_ERROR, "orcad: Broken output! Value contains space, but it cannot be escaped: \"%s\"\n", str);
	}

	fputs(str, f);
}

/* Export abstract components and connected nets */
static void orcad_export_comps_and_nets(FILE *f, csch_abstract_t *abs)
{
	htsp_entry_t *e, *p;
	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;

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

		if(fp==NULL)
		{
			fp = "unknown_fp";
			rnd_message(RND_MSG_ERROR, "orcad: no footprint is set for \"%s\"\n", refdes);
		}

		dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_DEVICE);
		if(dev==NULL) dev = sch_nle_get_alt_attr(&comp->hdr.attr, SCH_NLE_ALTATTR_VALUE);
		if(dev==NULL) dev = "X";

		fprintf(f, " (E%li ", comp->hdr.aid);
		orcad_print_value(f, fp);
		fputc(' ', f);
		orcad_print_value(f, refdes);
		fputc(' ', f);
		orcad_print_value(f, dev);
		fprintf(f, "\r\n");

		/* Print terminals with net names */
		for(p = htsp_first(&comp->ports); p != NULL; p = htsp_next(&comp->ports, p)) {
			const csch_aport_t *port = p->value;
			const char *pinnums = sch_nle_get_pinnum(port);

			csch_anet_t* net = port->conn.net;
			const char* netname;

			if(!net || net->hdr.omit)
				continue;

			netname = sch_nle_get_netname(net);

			SCH_NLE_FOREACH_PINNUM(pinnums, my_num,
				fprintf(f, "  (");
				orcad_print_value(f, my_num);
				fputc(' ', f);
				orcad_print_value(f, netname);
				fprintf(f, ")\r\n");
			);
		}

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

/* Export netlist from the abstract model */
static int orcad_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 = rnd_fopen(hidlib, fn, "w");
	if (f == NULL)
		return -1;

	fprintf(f, "( { OrCAD/PCB II Netlist Format\r\n");
	fprintf(f, "%s          Revised: 2/9/2025\r\n", fn);
	fprintf(f, "%*s          Revision: A\r\n", (int)strlen(fn), "");
	fprintf(f, "\r\n\r\n\r\n\r\n\r\n\r\n");
	fprintf(f, "Time Stamp - }\r\n");
	orcad_export_comps_and_nets(f, abs);
	fprintf(f, ")\r\n");

	fclose(f);
	return 0;
}

#include "hid_impl.c"

int pplg_check_ver_export_orcad(int ver_needed) { return 0; }

void pplg_uninit_export_orcad(void)
{
	csch_plug_io_unregister(&eorcad_net);
	rnd_export_remove_opts_by_cookie(orcad_cookie);
	rnd_hid_remove_hid(&orcad_hid);
}

int pplg_init_export_orcad(void)
{
	RND_API_CHK_VER;

	eorcad_net.name = "export to Orcad";
	eorcad_net.export_prio = orcad_export_prio;
	eorcad_net.export_project_abst = orcad_export_project_abst;
	eorcad_net.ext_export_project = ".net";
	csch_plug_io_register(&eorcad_net);


	rnd_hid_nogui_init(&orcad_hid);

	orcad_hid.struct_size = sizeof(rnd_hid_t);
	orcad_hid.name = "orcad";
	orcad_hid.description = "Exports project's Orcad netlist";
	orcad_hid.exporter = 1;

	orcad_hid.get_export_options = orcad_get_export_options;
	orcad_hid.do_export = orcad_do_export;
	orcad_hid.parse_arguments = orcad_parse_arguments;
	orcad_hid.argument_array = orcad_values;

	orcad_hid.usage = orcad_usage;

	rnd_hid_register_hid(&orcad_hid);
	rnd_hid_load_defaults(&orcad_hid, orcad_options, NUM_OPTIONS);


	return 0;
}

