/*
 *                            COPYRIGHT
 *
 *  sch-rnd - modular/flexible schematics editor - standard device mapper
 *  Copyright (C) 2022 Tibor 'Igor2' Palinkas
 *
 *  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
 */

/*** devmap parser ***/

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

static ldch_data_t *devmap_parse(ldch_high_parser_t *parser, void *call_ctx, ldch_file_t *file)
{
	ldch_data_t *data;
	devmap_t *devmap;
	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, "std_devmap.v1") != 0)) {
		rnd_message(RND_MSG_ERROR, "devmap: invalid root node in '%s'; expected 'ha:std_devmap.v1'\n", file->real_name);
		return NULL;
	}

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

	return data;
}

static void devmap_free_payload(ldch_data_t *data)
{
	devmap_t *devmap = (devmap_t *)&data->payload;

	csch_attrib_uninit(&devmap->comp_attribs);
}

