/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - (pin alternate) function map
 *  Copyright (C) 2023 Tibor 'Igor2' Palinkas
 *
 *  (Supported by NLnet NGI0 Entrust Fund in 2023)
 *
 *  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 <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <libfungw/fungw.h>
#include <genht/htsp.h>
#include <genht/hash.h>
#include <load_cache/load_cache.h>
#include <libcschem/config.h>
#include <libcschem/abstract.h>
#include <libcschem/concrete.h>
#include <libcschem/cnc_grp.h>
#include <libcschem/engine.h>
#include <libcschem/actions_csch.h>
#include <libcschem/attrib.h>
#include <libcschem/libcschem.h>
#include <libcschem/util_lib_fs.h>
#include <libcschem/util_loclib.h>
#include <libcschem/plug_library.h>
#include <libcschem/project.h>
#include <libcschem/project_p4.h>
#include <libcschem/event.h>
#include <libcschem/util_parse.h>
#include <librnd/core/misc_util.h>
#include <librnd/core/actions.h>
#include <librnd/core/compat_misc.h>
#include <librnd/core/safe_fs.h>
#include <librnd/core/plugins.h>
#include <librnd/core/conf_multi.h>

#include <plugins/sch_dialogs/quick_attr_util.h>
#include <plugins/lib_anymap/lib_anymap.h>

#include "funcmap_conf.h"
#include "conf_internal.c"

static conf_funcmap_t funcmap_conf;
static csch_p4cfg_t p4_funcmap;
static csch_lib_backend_t be_funcmap_lht;
static gds_t funcmap_tmp_gds, funcmap_tmp_gds2;

#define funcmap_get_anymap(sheet) \
	((anymap_ctx_t *)csch_p4_get_by_sheet(&p4_funcmap, sheet))

typedef anymap_obj_t funcmap_t;

static const char funcmap_cookie[] = "funcmap";
static csch_lib_master_t *devmaster;

#include "parse.c"
#include "loclib.c"
#include "libs.c"
#include "preview.c"
#include "fmparse.c"
#include "compiler.c"
#include "dlg_funcmap.c"
#include "fmdrc.c"

static int on_load(fgw_obj_t *obj, const char *filename, const char *opts)
{
	fgw_func_reg(obj, "compile_component1", funcmap_compile_comp1);
	fgw_func_reg(obj, "compile_port", funcmap_compile_port);

	return 0;
}

static const fgw_eng_t fgw_funcmap_eng = {
	"funcmap",
	csch_c_call_script,
	NULL,
	on_load,
	NULL /* on_unload */
};

const char csch_acts_quick_attr_funcmap[] = "quick_attr_funcmap(objptr)";
const char csch_acth_quick_attr_funcmap[] = "Quick Attribute Edit for funcmap using the funcmap library";
fgw_error_t csch_act_quick_attr_funcmap(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	rnd_design_t *hidlib = RND_ACT_DESIGN;
	csch_sheet_t *sheet = (csch_sheet_t *)hidlib;
	csch_cgrp_t *grp;
	fgw_arg_t ares, args[4];
	int ret;

	QUICK_ATTR_GET_GRP(grp, "quick_attr_funcmap");

	args[1].type = FGW_STR;
	args[1].val.cstr = "funcmap";
	args[2].type = FGW_STR;
	args[2].val.cstr = "sheet";
	args[3].type = FGW_STR;
	args[3].val.cstr = "modal";

	ret = rnd_actionv_bin(&sheet->hidlib, "librarydialog", &ares, 4, args);
	if ((ret == 0) && ((ares.type & FGW_STR) == FGW_STR)) {
		csch_source_arg_t *src;
		char *path = ares.val.str, *sep = NULL;

		if ((path != NULL) && (*path != '\0'))
			sep = strrchr(path, '/');
		if (sep != NULL) {
			char *end = strrchr(sep+1, '.');
			if ((end != NULL) && (rnd_strcasecmp(end, ".funcmap") == 0))
				*end = '\0';

			src = csch_attrib_src_p("funcmap", "manually picked from the funcmap lib");
			csch_attr_modify_str(sheet, grp, -CSCH_ATP_USER_DEFAULT, "funcmap", sep+1, src, 1);
/*			rnd_trace("new funcmap val: '%s'\n", sep+1);*/
		}
	}
	fgw_arg_free(&rnd_fgw, &ares);


	RND_ACT_IRES(1);
	return 0;
}


static const char csch_acts_FuncmaplibRehash[] = "FuncmaplibRehash()";
static const char csch_acth_FuncmaplibRehash[] = "Rebuild the in-memory tree of funcmaps";
static fgw_error_t csch_act_FuncmaplibRehash(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	csch_sheet_t *sheet = CSCH_ACT_SHEET;
	csch_lib_master_t *master = csch_lib_get_master("funcmap", 1);

	csch_lib_clear_sheet_lib(sheet, master->uid);
	csch_lib_add_all(sheet, master, &funcmap_conf.plugins.funcmap.search_paths, 1);
	rnd_event(&sheet->hidlib, CSCH_EVENT_LIBRARY_CHANGED, NULL);
	RND_ACT_IRES(0);
	return 0;
}

static const char csch_acts_FuncmaplibCleanLocal[] = "FuncmaplibCleanLocal()";
static const char csch_acth_FuncmaplibCleanLocal[] = "Remove all local-lib funcmaps from the current sheet; they are re-loaded from external libs into the local lib upon the next compilation. Useful to refresh local lib from disk.";
static fgw_error_t csch_act_FuncmaplibCleanLocal(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	csch_sheet_t *sheet = CSCH_ACT_SHEET;
	long cnt = 0, n, i;
	csch_lib_root_t *libroot;
	csch_lib_master_t *master = csch_lib_get_master("funcmap", 0);
	csch_cgrp_t *root_grp;

	libroot = sheet->local_libs.array[master->uid];
	for(n = 0; n < libroot->roots.used; n++) {
		csch_lib_t *root = libroot->roots.array[n];
		if (strcmp(root->name, "<local>") == 0) {
			for(i = root->children.used-1; i >= 0; i--) {
				csch_lib_t *le = root->children.array[i];
				csch_lib_remove(le);
				cnt++;
			}
			break;
		}
	}

	/* remove from indirect */
	root_grp = csch_loclib_get_root(sheet, master, NULL, 0, NULL);
	if (root_grp != NULL)
		csch_cgrp_clear(root_grp);

	rnd_message(RND_MSG_INFO, "Removed %ld funcmap(s) from the local lib of the sheet\n", cnt);

	rnd_event(&sheet->hidlib, CSCH_EVENT_LIBRARY_CHANGED, NULL);
	RND_ACT_IRES(0);
	return 0;
}


static void funcmap_sheet_postload_ev(rnd_design_t *hidlib, void *user_data, int argc, rnd_event_arg_t argv[])
{
	csch_sheet_t *sheet = (csch_sheet_t *)hidlib;
	csch_lib_add_all(sheet, devmaster, &funcmap_conf.plugins.funcmap.search_paths, 0);
	csch_lib_add_local(sheet, devmaster);
}

static rnd_action_t funcmap_action_list[] = {
	{"quick_attr_funcmap", csch_act_quick_attr_funcmap, csch_acth_quick_attr_funcmap, csch_acts_quick_attr_funcmap},
	{"FuncmaplibRehash", csch_act_FuncmaplibRehash, csch_acth_FuncmaplibRehash, csch_acts_FuncmaplibRehash},
	{"FuncmaplibCleanLocal", csch_act_FuncmaplibCleanLocal, csch_acth_FuncmaplibCleanLocal, csch_acts_FuncmaplibCleanLocal},
	{"FuncmapComponentDialog", csch_act_FuncmapComponentDialog, csch_acth_FuncmapComponentDialog, csch_acts_FuncmapComponentDialog},
	{"FuncmapPortDialog", csch_act_FuncmapPortDialog, csch_acth_FuncmapPortDialog, csch_acts_FuncmapPortDialog},
	{"FuncmapChange", csch_act_FuncmapChange, csch_acth_FuncmapChange, csch_acts_FuncmapChange},
	{"FuncmapPrintTable", csch_act_FuncmapPrintTable, csch_acth_FuncmapPrintTable, csch_acts_FuncmapPrintTable}
};

/*** p4 ***/


static void funcmap_p4_project_init(csch_p4cfg_t *p4, csch_project_t *prj)
{
	/* initialize view-local cache */
	anymap_ctx_t *ctx = calloc(sizeof(anymap_ctx_t), 1);
	ctx->name = ctx->attr_key = "funcmap";
	ctx->eng_src_name = "funcmap";
	ctx->be = &be_funcmap_lht;
	ctx->sheet_init = funcmap_sheet_init;
	ldch_init(&ctx->maps);
	ctx->maps.load_name_to_real_name = funcmap_lib_lookup;
	ctx->low_parser = ldch_lht_reg_low_parser(&ctx->maps);
	ctx->high_parser = ldch_reg_high_parser(&ctx->maps, "funcmap");
	ctx->high_parser->parse = funcmap_parse;
	ctx->high_parser->free_payload = funcmap_free_payload;

	csch_p4_set_by_project(p4, prj, ctx);
}

static void funcmap_p4_project_uninit(csch_p4cfg_t *p4, csch_project_t *prj)
{
	anymap_ctx_t *ctx = csch_p4_get_by_project(p4, prj);
	ldch_uninit(&ctx->maps);
	vtp0_uninit(&ctx->ssyms);
	free(ctx);
}


/*** plugin ***/

int pplg_check_ver_funcmap(int ver_needed) { return 0; }

void pplg_uninit_funcmap(void)
{
	rnd_event_unbind_allcookie(funcmap_cookie);
	rnd_remove_actions_by_cookie(funcmap_cookie);
	rnd_conf_plug_unreg("plugins/funcmap/", funcmap_conf_internal, funcmap_cookie);
	csch_p4_unreg_plugin(&p4_funcmap);
	gds_uninit(&funcmap_tmp_gds);
	gds_uninit(&funcmap_tmp_gds2);
}

int pplg_init_funcmap(void)
{
	RND_API_CHK_VER;

	fgw_eng_reg(&fgw_funcmap_eng);

	RND_REGISTER_ACTIONS(funcmap_action_list, funcmap_cookie);

	devmaster = csch_lib_get_master("funcmap", 1);
	be_funcmap_lht.name = "funcmap";
	be_funcmap_lht.realpath = funcmap_lht_realpath;
	be_funcmap_lht.map = funcmap_lht_map;
	be_funcmap_lht.map_local = funcmap_lht_map_local;
	be_funcmap_lht.load = funcmap_lht_load;
	be_funcmap_lht.preview_text = funcmap_lht_preview_text;
	be_funcmap_lht.free = anymap_lht_free;
	be_funcmap_lht.loc_refresh_from_ext = funcmap_loc_refresh_from_ext;
	be_funcmap_lht.loc_list = funcmap_loc_list;


	csch_lib_backend_reg(devmaster, &be_funcmap_lht);

	rnd_event_bind(CSCH_EVENT_SHEET_POSTLOAD, funcmap_sheet_postload_ev, NULL, funcmap_cookie);
	rnd_event_bind(CSCH_EVENT_DRC_RUN, funcmap_drc_ev, NULL, funcmap_cookie);

	rnd_conf_plug_reg(funcmap_conf, funcmap_conf_internal, funcmap_cookie);
#define conf_reg(field,isarray,type_name,cpath,cname,desc,flags) \
	rnd_conf_reg_field(funcmap_conf, field,isarray,type_name,cpath,cname,desc,flags);
#include "funcmap_conf_fields.h"

	p4_funcmap.project_init = funcmap_p4_project_init;
	p4_funcmap.project_uninit = funcmap_p4_project_uninit;

	csch_p4_reg_plugin(&p4_funcmap);

	return 0;
}

