#
#					ITSV GmbH
#	CCDB - Command and Control Database
#
#	FILE:			dquerymfile_xls2csv.txt
#	DESCRIPTION:	DQUERY definitions for DQUERY xls2csv
#					this query takes an XLS from a managed file and creates another managed file with the contents in CSV
#
@querytitle			XLS-Datei in CSV konvertieren
@querydescription	Konvertiert eine Excel-Datei (XLS, xlsx) aus einem managed file und erzeugt eine CSV-Datei daraus
@group				DATAFILE
@attributenames		mfileid:mfileid,newmfattribs:string:newmfattribsoptions
@newmfattribsoptions {
	labeltext:		"CSV-Managed-File-Attribute",
	typedesc:		"JSON-Format Attribute für neu erzeugtes CSV-managed-File",
	is_optional:	true }
@querytype			function
@function			seqtrans.seqtrans

~query.tsteps

#
#	<<TSTEPNUM:0>>: check init
#
if 		(this.init_done) 
goto	record_proper

#
#	<<TSTEPNUM:1>>: init
#
qexpression
	this.outlist = new Array();
	this.fieldsep = ";";
	this.linesep = "\n";
	let cl = new Array();
	for (let ci=0; ci<this.inputresult.metaData.length; ci++) {
		cl.push(this.inputresult.metaData[ci].name);
	}
	this.outlist.push(cl.join(this.fieldsep));
	this.recstoprocess = this.records_to_process;
	this.recsprocessed = 0;
	this.init_done = true;
 
#
# <<TSTEPNUM:2>>:
#
record_proper:
qexpression
	if ((this.recnum%100)==0) logger.debug(this.phead("xlsrecord")+".recordstoprocess="+this.records_to_process+".current_record="+this.recnum);
	this.outlist.push(this.inputresult.getRow(this.recnum).join(this.fieldsep));
	this.recsprocessed++;

#
# <<TSTEPNUM:3>>:
#
if		(!this.is_last_record)
goto	record_end

#
# <<TSTEPNUM:4>>: 
#
aexpression
	this.ppush([this.phead("allrecsread"),"","",""]);
	let opts = {	extension:	"csv"	};
	if (this.query.newmfattribs) opts.mfileattribs = this.query.newmfattribs;
	mfile.saveToMfile(this.session,'gencsv',this.outlist.join(this.linesep),
		{	extension:	"csv"	},
		function(err,res) {
			if (err) {
				this.errcoll.collect(err,"Error saving output data to managed file",res);
				this();
				return;
			}
			if (res && res.resulttype=="object" && res.resultobject && res.resultobject.mfileid) {
				this.ppush([this.phead("finished"),{ rawhtml: "MFILEID=<a href=\"/dquery?dataname=SHOWFILE?mfileid="+res.mfileid+"\">"+res.resultobject.mfileid+"</a>"},"recsprocessed="+this.recsprocessed,res]);
			} else {
				this.ppush([this.phead("finished_error"),"result malformed","recsprocessed="+this.recsprocessed,res]);
			}
			this();
		}.bind(this)
	)
	

#
# <<TSTEPNUM:5>>:
#
record_end:
end
