/*
 *                            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
 */

/*** funcmap library handling ***/

static char *funcmap_lib_lookup(ldch_ctx_t *ctx, const char *load_name, ldch_low_parser_t *low, ldch_high_parser_t *high, void *low_call_ctx, void *high_call_ctx)
{
/*	csch_hook_call_ctx_t *cctx = high_call_ctx;     for cctx->project */
/*	fgw_obj_t *obj = ctx->user_data;*/
	csch_lib_t *le;

	/* if full path is known */
	if (strchr(load_name, '/') != NULL)
		return rnd_strdup(load_name);

	TODO("we shouldn't search master, only sheet's funcmap libs, but the"
	     "abstract model doesn't have sheets");
	le = csch_lib_search_master(devmaster, load_name, CSCH_SLIB_STATIC);
	if (le == NULL) {
		char *load_name2 = rnd_concat(load_name, ".funcmap", NULL);
		le = csch_lib_search_master(devmaster, load_name2, CSCH_SLIB_STATIC);
		free(load_name2);
	}
/*	rnd_trace("funcmap lookup: %s -> %p\n", load_name, le);*/

	return le == NULL ? NULL : rnd_strdup(le->realpath);
}

/* effectively a test-parse */
csch_lib_type_t funcmap_lht_file_type(rnd_design_t *hl, const char *fn)
{
	FILE *f;
	int n;
	csch_lib_type_t res = CSCH_SLIB_invalid;

	f = rnd_fopen(hl, fn, "r");
	if (f == NULL)
		return res;

	for(n = 0; n < 16; n++) {
		char *s, line[1024];
		s = fgets(line, sizeof(line), f);
		if (s == NULL) break;
		if (strstr(s, "ha:funcmap.v") == 0) {
			res = CSCH_SLIB_STATIC;
			break;
		}
	}
	fclose(f);
	return res;
}


static char *funcmap_lht_realpath(rnd_design_t *hl, const char *root)
{
	/* accept only non-prefixed paths for now */
	if (strchr(root, '@') != NULL)
		return NULL;

	return csch_lib_fs_realpath(hl, root);
}

static int funcmap_lht_map(rnd_design_t *hl, csch_lib_t *root_dir)
{
	gds_t tmp = {0};
	gds_append_str(&tmp, root_dir->realpath);
	csch_lib_fs_map(hl, &be_funcmap_lht, root_dir, &tmp, funcmap_lht_file_type);
	gds_uninit(&tmp);
	return 0;
}
