include "primitives.alh"
include "modelling.alh"
include "library.alh"

Void function visit_ftg(ftg : Element, root : Element, path : String, current : Element):
	log("Visit FTG: " + path)
	if (dict_in(current, "source")):
		// Is a transformation, and therefore an edge for the FTG
		if (bool_not(dict_in(ftg["model"], path))):
			if (bool_not(dict_in(ftg["model"], current["source"]))):
				visit_ftg(ftg, root, current["source"], root[current["source"]])

			if (bool_not(dict_in(ftg["model"], current["target"]))):
				visit_ftg(ftg, root, current["target"], root[current["source"]])

			instantiate_link(ftg, "Transformation", path, current["source"], current["target"])
			instantiate_attribute(ftg, path, "location", path)
	else:
		// Is a model, and therefore a node for the FTG
		if (bool_not(dict_in(ftg["model"], path))):
			instantiate_node(ftg, "Formalism", path)
			instantiate_attribute(ftg, path, "location", path)

	return !

Element function create_ftg(root : Element):
	Element queue
	Element current
	Element submodels
	Element ftg
	String path
	String submodel

	queue = create_node()
	set_add(queue, create_tuple("models", root))
	ftg = instantiate_model(import_node("models/FTG"))

	while (read_nr_out(queue) > 0):
		current = set_pop(queue)
		path = current[0]
		current = current[1]
		log("Check node: " + cast_e2s(current))
		if (dict_in(current, "__hierarchy_node" )):
			log("IS HIERARCHY: " + path)
			submodels = dict_keys(current)
			// Is a browser structure, and therefore not part of the FTG
			while (read_nr_out(submodels) > 0):
				submodel = set_pop(submodels)
				set_add(queue, create_tuple((path + "/") + submodel, current[submodel]))
		else:
			log("IS MODEL: " + path)
			visit_ftg(ftg, root, path, current)

	return ftg!
