#
#		ITSV GmbH
#		CCDB - Command and Control Database
#
#	FILE:			dquerymfile_regMVBRFAUSWSOID.txtObjDecode
#	DESCRIPTION:	dquery definition for regMVBRFAUSWSOID
#
# 
@group				SVCLMVBRFAUSWDATALOAD
@querytitle 		registriere noch unbekannte LSW aus CCMVBRFAUSW in SVCLRWLSW
@querydescription	registriert zu jeder SOID aus CCMVBRFAUSW, die noch nicht in SVCLRWSOID aufzufinden ist,
					einen SOID-Eintrag in SVCLRWSOID. 
					Wenn der dazugehörige Eintrag noch nicht in SVCLRWLSW aufzufinden ist, dazu einen LSW-Eintrag in SVCLRWLSW
					Zum Auffinden der LSW werden die in den vorhandenen LSW-Einträgen hinterlegten "soidrex"-Regular-Expressions
					geprüft.
@attributenames			allowCreateLSW:noyes:{{allowCreateLSWoptions}}
@allowCreateLSWoptions	{"labeltext":"Anlegen neuer LWS erlaubt",
                         "typedesc":"Wenn JA, dürfen neue, künstliche LSW angelegt werden, wenn NEIN, wird die Verarbeitung abgebrochen, wenn keine bereits vorhandene LSW gefunden wird",
						 "is_optional":"true",
						 "default":"N"}
@querytype			function
@function			seqtrans.seqtrans
@sql_select			select distinct SOID from CCMVBRFAUSW where ((SOID is not null) and (SOID!='')) and ((LSWID is null) or LSWID='')

~query.tsteps

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

#
# <<TSTEPNUM:1>>: initialize, setup internal counters and constants
#
qexpression
	proc: {
		if (!this.init_done) {
			this.qname = this.query.dataname;
			this.ppfx = this.fname+"("+this.dataname+")";
			this.soidstoprocess = this.inputresult.getRowCount();
			if (!this.query.hasOwnProperty("allowCreateLSW")) {
				this.query.allowCreateLSW = false;
			} else {
				this.query.allowCreateLSW = aux.boolFromString(this.query.allowCreateLSW);
			}
			ppush(this,[this.ppfx+"_started","SOIDS_TO_PROCESS="+this.soidstoprocess,"",""]);
			this.recsprocessed = 0;
			this.soidsprocessed = 0;
			this.newsoidsregistered = 0;
			this.newlswsregistered = 0;
			this.knownsoidsfound = 0;
		}
	}
	
#
# <<TSTEPNUM:2>>: initialize: get info about already present LSW
#
sql				select LSWID,LSWHID,LSWATTRIBS from SVCLRWLSW
result_varname	lswres
post_qexpression
	proc: {
		let li, lr, as;
		this.knownLSWs = {};
		this.SOIDrexs = new Array();
		for (li=0; li<this.lswres.getRowCount(); li++) {
			lr = this.lswres.getRowObject(li);
			this.knownLSWs[lr.LSWID] = { LSWID: lr.LSWID, LSWHID: lr.LSWHID };
			as = aux.txtObjDecode(lr.LSWATTRIBS,{dbg:true});
			if (as.error) {
				this.errcoll.collect(as.error,"Error parsing JSON \""+lr.LSWATTRIBS+"\"");
				break proc;
			} else {
				this.knownLSWs[lr.LSWID].attributes = as;
			}
			if (this.knownLSWs[lr.LSWID].attributes.soidrex) {
				this.SOIDrexs.push({ rex: new RegExp(this.knownLSWs[lr.LSWID].attributes.soidrex), lswid: lr.LSWID });
			}
		}
		this.init_done = true;
	}

#
# <<TSTEPNUM:3>>: process current record
#
record_proper:
qexpression
	this.have_soid = false;
	this.have_lswid = false;
			
#
# <<TSTEPNUM:4>>: check SVCLRWSOID if we have a matching SOID
#
sql				select SOID,LSWID from SVCLRWSOID where SOID=::SOID::
named_params	SOID
result_varname	chksoidres
post_qexpression
	proc: {
		this.have_soid = false;
		if (this.chksoidres.getRowCount()>0) {
			this.have_soid = true;
			if (!this.have_lswid) {
				let lswid = this.chksoidres.getCellValue(0,1);
				if (lswid) {
					this.cdata.LSWID = lswid;
					this.have_lswid = true;
				} else {
					this.errcoll.collect(null,"found SOID entry, but has no LSWID",this.chksoidres);
					break proc;
				}
			}
		}
	}

#
# <<TSTEPNUM:5>>: if SOID already known, skip creating new SOID entry
#
if 		(this.have_soid)
goto	got_SOID

#
# <<TSTEPNUM:6>>: no known SOID, check known LSWs if we have a matching SOIDREX
#
qexpression
	let cdone = false;
	let rexi = 0;
	this.foundLSWID = null;
	let m;
	while (!cdone) {
		if (rexi>=this.SOIDrexs.length) {
			break;
		}
		if (!this.SOIDrexs[rexi].rex) break;
		m = this.SOIDrexs[rexi].rex.exec(this.cdata.SOID);
		if (m) {
			this.cdata.LSWID = this.SOIDrexs[rexi].lswid;
			this.have_lswid = true;
			ppush(this,[this.fname+"("+this.dataname+")_SOIDREXMATCH","SOID="+this.cdata.SOID,"REX="+this.SOIDrexs[rexi].rex,"LSWID="+this.cdata.LSWID]);
			cdone = true;
			break;
		}
		rexi++;
	}

#
# <<TSTEPNUM:7>>: no SOID, if we have a known LSWID, skip creating a new one
#
pre_qexpression
if 		(this.have_lswid)
goto	got_LSWID

#
# <<TSTEPNUM:8>>: need a new SOID and a new LSWID, first create new LSW
#
pre_qexpression
	proc: {
		this.cdata.LSWID = "LSW_"+aux.syncUniqueNowID();
		this.cdata.LSWHID = "LSWH_"+aux.syncUniqueNowID();
		this.cdata.LSWATTRIBS = "{}";
		if (!this.query.allowCreateLSW) {
			this.errcoll.collect(null,"would need new LSW, but we don't want to",{ SOID: getcvar(this,"SOID") });
			break proc;
		}
	}
sql				INSERT INTO SVCLRWLSW(LSWID,LSWHID,LSWATTRIBS) values(::LSWID::,::LSWHID::,::LSWATTRIBS::)
named_params	LSWID,LSWHID,LSWATTRIBS
post_qexpression
	this.newlswsregistered++;
	ppush(this,[this.ppfx+"_NEW_LSW_CREATED",
				"FROM_SOID="+this.cdata.SOID,
				"LSW_ID="+this.cdata.LSWID,
				"LSWH_ID="+this.cdata.LSWHID]);

#
# <<TSTEPNUM:9>>: create new SOID entry, LSWID already known
#
got_LSWID:
sql				insert into SVCLRWSOID(SOID,LSWID) values(::SOID::,::LSWID::)
named_params	SOID,LSWID
post_qexpression
	this.newsoidsregistered++;
	ppush(this,[this.ppfx+"_NEW_SOID_CREATED","NEW_SOID="+this.cdata.SOID,"LSW_ID="+this.cdata.LSWID,""]);

	
#
# <<TSTEPNUM:10>>: SOID and LSW are both there (either already there or created now), link LSWID to records in CCMVBRFAUSW
#
got_SOID:
sql				update CCMVBRFAUSW set LSWID=::LSWID:: where SOID=::SOID:: and (LSWID is null or LSWID='')
named_params	LSWID,SOID
result_varname	updres
post_qexpression
	proc: {
		this.recsprocessed += this.updres.resultobject.affectedRows;
		ppush(this,[this.ppfx+"_RECSREGISTERED","SOID="+this.cdata.SOID,"LSWID="+this.cdata.LSWID,"RECORDS_UPDATED="+this.updres.resultobject.affectedRows]);
		if (this.updres.resultobject.affectedRows<1) {
			this.errcoll.collect(null,"update LSWID did not affect any rows, this is dubious",{cdata: this.cdata, upres: this.updares, named_params: this.named_params, sql: this.populated_sql});
			break proc;
		}
	}

#
# <<TSTEPNUM:11>>: nothing more to be done, check if last record
#
pre_qexpression
	this.soidsprocessed++;
if (!this.is_last_record)
goto record_done

#
# <<TSTEPNUM:12>>: finish up protocol
#
qexpression
	ppush(this,	[this.ppfx+"_finished",
	            "SOIDS_PROCESSED="+this.soidsprocessed,
				"KNOWN_SOIDS_ENCOUNTERED="+this.knownsoidsfound+", NEW_SOIDS_REGISTERED="+this.newsoidsregistered,
				"NEW_LSWs_REGISTERED="+this.newlswsregistered]);

#
# <<TSTEPNUM:13>>: end of record processing
#
record_done:
end

	