/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - alternate function mapper
 *  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 parser ***/

static void parse_error(void *ectx, lht_node_t *n, const char *msg)
{
	rnd_message(RND_MSG_ERROR, "funcmap: parse error '%s' near %ld:%ld\n", msg, n->line, n->col);
}

static ldch_data_t *funcmap_parse(ldch_high_parser_t *parser, void *call_ctx, ldch_file_t *file)
{
	ldch_data_t *data;
	funcmap_t *funcmap;
	lht_doc_t *doc = ldch_lht_get_doc(file);

	if ((doc->root == NULL) && rnd_is_dir(NULL, file->real_name))
		return NULL; /* happens on refresh on a dir */

	if ((doc->root == NULL) || (doc->root->type != LHT_HASH) || (strcmp(doc->root->name, "funcmap.v1") != 0)) {
		rnd_message(RND_MSG_ERROR, "funcmap: invalid root node in '%s'; expected 'ha:funcmap.v1'\n", file->real_name);
		return NULL;
	}

	data = ldch_data_alloc(file, parser, sizeof(funcmap_t));
	funcmap = (funcmap_t *)&data->payload;
	csch_attrib_init(&funcmap->comp_attribs);
	if (csch_lht_parse_attribs(&funcmap->comp_attribs, lht_dom_hash_get(doc->root, "comp_attribs"), parse_error, NULL) != 0) {
		rnd_message(RND_MSG_ERROR, "funcmap: failed to load any component attributes from '%s''\n", file->real_name);
		ldch_data_free(parser->ctx, data);
		return NULL;
	}

	return data;
}

static void funcmap_free_payload(ldch_data_t *data)
{
	funcmap_t *funcmap = (funcmap_t *)&data->payload;

	csch_attrib_uninit(&funcmap->comp_attribs);
}

