#
#			ITSV GmbH
#	CCDB - Command and Control Database
#
#	FILE:			dquerymfile_textfragtree.txt
#	DESCRIPTION:	DQUERY definition for DQUERY textfragtree
#
@querytitle			Textfragmente in Baumansicht
@querydescription	Diese Abfrage stellt alle Textfragmente in ihrem Verhältnis als Baum-Ansicht dar
@group				ADMINTEXTFRAG
@querytype			dbselect
@sql				select type,ident,parent,child_index,frag_index,version,data from CCTEXTFRAG
@format				none
@post_query
	let sqlresult = that.result;
	logger.debug("textfragtree.SQLRESULT: "+aux.objTxt(sqlresult));
	let textids = {};
	let cr, parid, prec;
	for (let ri=0; ri<sqlresult.getRowCount(); ri++) {
		cr = that.result.getRowObject(ri);
		if (!textids[cr.ident]) {
			textids[cr.ident] = { ident: cr.ident, parts: new Array(), children: {} };
		}
	}
	for (let ri=0; ri<sqlresult.getRowCount(); ri++) {		/* now provide the linkage */
		cr = that.result.getRowObject(ri);
		parid = cr.parent;
		if (!parid) {												/* we have no parent, are we the legit root? */
			if (textids._root) {									/* there is a root already registered */
				if (textids._root.ident==cr.ident) {				/* we're the root, all OK */
				} else {											/* there is already another root, WORRY */
					logger.error("text fragment with ident \""+record.ident+"\" has no parent, but root is already occupied by ident \""+textids._root.ident+"\"");
				}
			} else {												/* there's no root already, let us establish as root */
				textids._root = textids[cr.ident];
			}
		} else {													/* we have a parent, look if it's already there */
			prec = textids[cr.parent];
			if (prec) {
				if (!prec.children[cr.ident]) prec.children[cr.ident] = textids[cr.ident];
			} else {
				logger.error("text fragment with ident \""+cr.ident+"\" has parent \""+cr.parent+"\", but this does not exist");
			}
		}
		textids[cr.ident].parts.push(cr);
	}
	that.result = new aux.Result({ resulttype: "object", resultobject: textids._root});
