/*
 *                            COPYRIGHT
 *
 *  cschem - modular/flexible schematics editor - standard device mapper
 *  Copyright (C) 2019,2020,2022,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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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 <libcschem/operation.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 "std_devmap_conf.h"
#include "conf_internal.c"

static conf_std_devmap_t std_devmap_conf;
static csch_p4cfg_t p4_devmap;
static csch_lib_backend_t be_devmap_lht;

#define devmap_get_anymap(sheet) \
	((anymap_ctx_t *)csch_p4_get_by_sheet(&p4_devmap, sheet))

typedef anymap_obj_t devmap_t;

static const char devmap_cookie[] = "devmap";
static csch_lib_master_t *devmaster;

#include "parse.c"
#include "loclib.c"
#include "libs.c"
#include "preview.c"
#include "compiler.c"

static int on_load(fgw_obj_t *obj, const char *filename, const char *opts)
{
	fgw_func_reg(obj, "terminal_name_to_port_name", devmap_term2port);
	fgw_func_reg(obj, "symbol_joined_component", devmap_symbol_joined_comp);
	fgw_func_reg(obj, "compile_component1", devmap_compile_comp1);
	fgw_func_reg(obj, "compile_port", devmap_compile_port);

	return 0;
}

static const fgw_eng_t fgw_std_devmap_eng = {
	"std_devmap",
	csch_c_call_script,
	NULL,
	on_load,
	NULL /* on_unload */
};


const char csch_acts_quick_attr_devmap[] = "quick_attr_devmap(objptr)";
const char csch_acth_quick_attr_devmap[] = "Quick Attribute Edit for devmap using the devmap library";
fgw_error_t csch_act_quick_attr_devmap(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_devmap");

	args[1].type = FGW_STR;
	args[1].val.cstr = "devmap";
	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, ".devmap") == 0))
				*end = '\0';

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


	RND_ACT_IRES(1);
	return 0;
}

static const char csch_acts_DevmaplibRehash[] = "DevmaplibRehash()";
static const char csch_acth_DevmaplibRehash[] = "Rebuild the in-memory tree of devmaps";
static fgw_error_t csch_act_DevmaplibRehash(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("devmap", 1);

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

static const char csch_acts_DevmaplibCleanLocal[] = "DevmaplibCleanLocal()";
static const char csch_acth_DevmaplibCleanLocal[] = "Remove all local-lib devmaps 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_DevmaplibCleanLocal(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("devmap", 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, devmaster, NULL, 0, NULL);
	if (root_grp != NULL)
		csch_cgrp_clear(root_grp);

	rnd_message(RND_MSG_INFO, "Removed %ld devmap(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 devmap_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, &std_devmap_conf.plugins.std_devmap.search_paths, 0);
	csch_lib_add_local(sheet, devmaster);
}

#include "quick_attr_portmap.c"

static rnd_action_t devmap_action_list[] = {
	{"quick_attr_devmap", csch_act_quick_attr_devmap, csch_acth_quick_attr_devmap, csch_acts_quick_attr_devmap},
	{"quick_attr_portmap", csch_act_quick_attr_portmap, csch_acth_quick_attr_portmap, csch_acts_quick_attr_portmap},
	{"DevmaplibRehash", csch_act_DevmaplibRehash, csch_acth_DevmaplibRehash, csch_acts_DevmaplibRehash},
	{"DevmaplibCleanLocal", csch_act_DevmaplibCleanLocal, csch_acth_DevmaplibCleanLocal, csch_acts_DevmaplibCleanLocal}
};

/*** p4 ***/


static void devmap_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 = "devmap";
	ctx->eng_src_name = "std_devmap";
	ctx->be = &be_devmap_lht;
	ctx->sheet_init = devmap_sheet_init;
	ldch_init(&ctx->maps);
	ctx->maps.load_name_to_real_name = devmap_lib_lookup;
	ctx->low_parser = ldch_lht_reg_low_parser(&ctx->maps);
	ctx->high_parser = ldch_reg_high_parser(&ctx->maps, "devmap");
	ctx->high_parser->parse = devmap_parse;
	ctx->high_parser->free_payload = devmap_free_payload;

	csch_p4_set_by_project(p4, prj, ctx);
}

static void devmap_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_std_devmap(int ver_needed) { return 0; }

void pplg_uninit_std_devmap(void)
{
	rnd_event_unbind_allcookie(devmap_cookie);
	rnd_remove_actions_by_cookie(devmap_cookie);
	rnd_conf_plug_unreg("plugins/std_devmap/", std_devmap_conf_internal, devmap_cookie);
	csch_p4_unreg_plugin(&p4_devmap);
}

int pplg_init_std_devmap(void)
{
	RND_API_CHK_VER;

	fgw_eng_reg(&fgw_std_devmap_eng);

	RND_REGISTER_ACTIONS(devmap_action_list, devmap_cookie);

	devmaster = csch_lib_get_master("devmap", 1);
	be_devmap_lht.name = "std_devmap";
	be_devmap_lht.realpath = devmap_lht_realpath;
	be_devmap_lht.map = devmap_lht_map;
	be_devmap_lht.map_local = devmap_lht_map_local;
	be_devmap_lht.load = devmap_lht_load;
	be_devmap_lht.preview_text = devmap_lht_preview_text;
	be_devmap_lht.free = anymap_lht_free;
	be_devmap_lht.loc_refresh_from_ext = devmap_loc_refresh_from_ext;
	be_devmap_lht.loc_list = devmap_loc_list;


	csch_lib_backend_reg(devmaster, &be_devmap_lht);

	rnd_event_bind(CSCH_EVENT_SHEET_POSTLOAD, devmap_sheet_postload_ev, NULL, devmap_cookie);

	rnd_conf_plug_reg(std_devmap_conf, std_devmap_conf_internal, devmap_cookie);
#define conf_reg(field,isarray,type_name,cpath,cname,desc,flags) \
	rnd_conf_reg_field(std_devmap_conf, field,isarray,type_name,cpath,cname,desc,flags);
#include "std_devmap_conf_fields.h"

	p4_devmap.project_init = devmap_p4_project_init;
	p4_devmap.project_uninit = devmap_p4_project_uninit;

	csch_p4_reg_plugin(&p4_devmap);

	return 0;
}

