#
#	ITSV-GmbH
#	CCDB - Command and Control Database
#
#	FILE:				dquerymfile_dumpquerymfile
#	DESCRIPTION:		definition for DQUERY "dumpquerymfile"
#						dumps query definition of query parameter <queryname> to managed file dquerymfile_<queryname>.txt
#						and registers the managed file
#
@querytitle			Abfrage-Definition aus CCRW nach managed file auslagern
@querydescription	dumps query definition of query parameter <queryname> to managed file
@group				QUERIES
@attributenames		queryname:queryname
@querytype			function
@function			seqtrans.seqtrans
@sql_select			select RWNAME from CCRW where RWTYP='DQUERY' and RWPARENT='QUERIES' and RWNAME=::queryname::
@setup.qexpression
	proc: {
		this.qatoString = function(qanam,qaval) {
			qaval = qaval.replace(/\r\n/g,"\n");
			qaval = qaval.replace(/\n\r/g,"\n");
			qaval = qaval.replace(/\r/g,"\n");
			let qalines = qaval.split("\n");
			for (let i=0; i<qalines.length; i++) {
				qalines[i] = qalines[i].trim();
				if (qalines[i].length<1) {
					qalines[i] = "\\";
				}
			}
			return "@"+qanam+"\r\n\t\t"+qalines.join("\r\n\t\t")+"\r\n";
		};
		if (this.inputresult.getRowCount()<1) {
			this.errcoll.collect(null,"query \""+this.query.queryname+"\" not found in CCRW",this.inputresult);
			break proc;
		}
	}

~query.tsteps

#
# <<TSTEPNUM:0>>: determine if initialized
#
if	(this.init_done)
goto	record_proper

#
# <<TSTEPNUM:1>>: initialize
#
qexpression
	proc: {
		if (!this.init_done) {
			this.qname = this.query.dataname;
			logger.debug(this.fname+"."+this.qname+".UDBG.t_init.query: "+aux.objTxt(this.query)+"...INPUTRESULT: "+aux.objTxt(this.inputresult));
			this.queriestoprocess = this.inputresult.getRowCount();
			this.protocol = new Array();
			this.protocol.push([this.fname+"("+this.qname+")_started","QUERIES_TO_PROCESS="+this.queriestoprocess,"",""]);
			this.queriesprocessed = 0;
			this.init_done = true;
			this.queryname = getcvar(this,"RWNAME",null);
			if (!this.queryname) {
				this.errcoll.collect(null,"Error in "+this.fname+"."+this.qname+": queryname not determinable",this.cdata);
				break proc;
			}
		}
	}

#
# <<TSTEPNUM:2>>: get all query attributes
#
record_proper:
sql 			select qr.RWNAME as "ID",
					qr.RWVALUE as "AbfrageName",
					qr.RWDESC as "Beschreibung",
					qa.RWNAME as "Eigenschaft", 
					(CASE WHEN qa.RWVALUE is null THEN '' ELSE qa.RWVALUE END) as "Wert", 
					CONCAT('{"action": "',(CASE WHEN qa.RWVALUE is null THEN '' ELSE 'DELETE' END),
						'", "attribute": "',qa.RWNAME,'", "key": "',qr.RWNAME,'"}')  as "DeleteAction"
				from CCRW qr
					left outer join CCRW qa on qa.RWTYP='DQUERYPARAM' and qa.RWPARENT=qr.RWNAME
				where qr.RWTYP='DQUERY' and qr.RWPARENT='QUERIES' and qr.RWNAME=::queryname::
named_params	queryname
result_varname	qires

#
# <<TSTEPNUM:3>>: check query info
#
qexpression
	proc: {
		if (this.qires.getRowCount()<2) {
			this.errcoll.collect(null,"Query \""+this.queryname+"\" has too few RW-records",this.qires);
			break proc;
		}
	}

#
# 4: extract query definition data and write to static physical file
#
qexpression
	proc: {
		this.cqid = this.qires.getCellValue(0,0);
		this.fdata  = "#\r\n";
		this.fdata += "#\t\tITSV GmbH\r\n";
		this.fdata += "#\tCCDB - Command and Control Database\r\n";
		this.fdata += "#\r\n";
		this.fdata += "#\tFILE:\t\tdquermfile_"+this.cqid+".txt\r\n";
		this.fdata += "#\tDESCRIPTION:\tDQUERY definition for CCDB DQUERY \""+this.cqid+"\"\r\n";
		this.fdata += "#\r\n";
		this.fdata += this.qatoString("querytitle",this.qires.getCellValue(0,1));
		this.fdata += this.qatoString("querydescription",this.qires.getCellValue(0,2));
		for (let ai=0; ai<this.qires.getRowCount(); ai++) {
			this.fdata += this.qatoString(this.qires.getCellValue(ai,3),this.qires.getCellValue(ai,4));
		}
		this.mfilepath = "../config/dquerymfile_"+this.queryname+".txt";
		fs.writeFileSync(this.mfilepath,this.fdata);	
	}

#
# <<TSTEPNUM:5>>: register static managed file by using sub-query "registerDqueryMfile"
#		ATTENTION: this modifies the standard behaviour of "registerDqueryMfile":
#			normally, it chains over to "showfile", but this invocation disables the chaining
#			and gets the result of the INSERT in the CCMFILES table done by "registerDqueryMfile"
#
query.dataname		registerDqueryMfile
query.queryname		@@queryname@@
query.return_to		__NOTHING__
post_qexpression
	this.mfresult = this.stepresult;
	
#
# <<TSTEPNUM:6>>: delete CCRW records for dumped query
#
sql				delete from CCRW where (RWTYP='DQUERY' and RWPARENT='QUERIES' and RWNAME=::queryname::)
									or (RWTYP='DQUERYPARAM' and RWPARENT=::queryname::)
named_params	queryname

#
# <<TSTEPNUM:7>>: update counters
#
qexpression
	this.protocol.push([this.fname+"("+this.qname+")_QUERY_PROCESSED","QUERYNAME="+this.cdata.queryname,"","MFILE_CREATED: "+aux.objTxt(this.mfresult)]);
	this.queriesprocessed++;

#
# <<TSTEPNUM:8>>: one record complete, check if last record
#
if 		(!this.is_last_record)
goto	record_done

#
# <<TSTEPNUM:9>>: create result from protocol
#
qexpression
	this.protocol.push([this.fname+"("+this.qname+")_finished","QUERIES_PROCESSED="+this.queriesprocessed,"",""]);
	this.result = new aux.Result({resulttype: 'dbresult', metaData: [{name: 'Info'},{name: 'parameter 1'},{name: 'parameter 2'},{name: 'parameter 3'}], rows: this.protocol});
	
#
# <<TSTEPNUM:10>>: end of record processing
#
record_done:
end
		
