/*
 * JSMin
 * Javascript Compressor
 * http://www.crockford.com/
 * http://www.smallsharptools.com/Projects/Packer/
*/

// V:\1.1.007\js\lib\ext-namirial\Ext.ux.Namirial.data.Synchronizer.js

Ext.namespace('Ext.ux');Ext.namespace('Ext.ux.Namirial');Ext.namespace('Ext.ux.Namirial.data');Ext.ux.Namirial.data.Synchronizer=Ext.extend(Ext.util.Observable,{actTable:'actions',reset:false,mantieniDichiarazione:false,constructor:function(c){Ext.apply(this,c);this.reset=c.reset||false;this.serverQueries=[];this.errors=[];this.arrayCfisc=[];this.addEvents('update','updateexception','synchronize','synchronizeexception','synctable','synccfisc');Ext.ux.Namirial.data.Synchronizer.superclass.constructor.call(this);this.setListeners();this.initTable();},initTable:function(reset){reset=reset||this.reset;if(reset||!this.gearsSysConn.queryBy("SELECT id FROM '"+this.actTable+"'")){this.createTable();}
this.table=this.gearsSysConn.getTable(this.actTable,'id');},createTable:function(){this.gearsSysConn.exec("DROP TABLE IF EXISTS '"+this.actTable+"'");this.gearsSysConn.createTable({name:this.actTable,key:'id',fields:[{name:'id',type:'int',unique:true,allowNull:false},{name:'CFISC',type:'string',allowNull:false},{name:'tabella',type:'text',allowNull:true},{name:'azione',type:'text',allowNull:false},{name:'errori',type:'boolean',allowNull:false,defaultValue:false}]});},addAction:function(action,cfisc,table){table=table||null;var check=true;var rec=this.gearsSysConn.query("SELECT * FROM "+this.actTable+" WHERE CFISC = '"+cfisc+"' AND tabella = '"+table+"' AND azione = '"+action+"'")
if(rec.totalRows==0){switch(action){case'update':var checkRec=this.gearsSysConn.query("SELECT * FROM "+this.actTable+" WHERE CFISC = '"+cfisc+"' AND tabella = '"+table+"' AND azione = 'insert'")
if(checkRec.totalRows>0){check=false;}
break;case'invalida':var checkRec=this.gearsSysConn.query("SELECT * FROM "+this.actTable+" WHERE CFISC = '"+cfisc+"' AND tabella = '"+ANAGRAFICA_TAB+"' AND (azione = 'insert' OR azione = 'update')")
if(checkRec.totalRows>0){check=false;}
break;case'delete':case'replace':this.gearsSysConn.exec("DELETE FROM "+this.actTable+" WHERE CFISC = '"+cfisc+"' AND tabella = '"+table+"'")
break;}}else{check=false;}
if(check){this.table.insert({CFISC:cfisc,azione:action,tabella:table});}},removeAllAction:function(cfisc){if(!Ext.isEmpty(cfisc)){this.gearsSysConn.exec("DELETE FROM azioni WHERE CFISC='"+cfisc+"'");}},generateServerQuery:function(cfisc,table){var sql=[];var rec=this.gearsDataConn.queryBy("SELECT * FROM "+table+" WHERE CFISC = '"+cfisc+"'");var azioni=this.table.selectBy("WHERE CFISC = '"+cfisc+"' AND tabella = '"+table+"'").rows;for(var j=0,azlen=azioni.length;j<azlen;j++){switch(azioni[j].azione){case'update':var clause;for(var i=0,len=rec.rows.length;i<len;i++){if(rec.rows[i].keyId!=undefined){delete(rec.rows[i].keyId);}
clause="[CFISC] = '"+cfisc+"'";sql.push(generateQuery(SERVER,table,rec.rows[i],UPDATE,clause));}
break;case'delete':sql.push("DELETE FROM "+table+" WHERE CFISC ='"+cfisc+"'");break;case'insert':for(var i=0,len=rec.rows.length;i<len;i++){if(rec.rows[i].keyId!=undefined){delete(rec.rows[i].keyId);}
sql.push(generateQuery(SERVER,table,rec.rows[i],INSERT));}
break;case'replace':sql.push("DELETE FROM "+table+" WHERE CFISC ='"+cfisc+"'");for(var i=0,len=rec.rows.length;i<len;i++){if(rec.rows[i].keyId!=undefined){delete(rec.rows[i].keyId);}
sql.push(generateQuery(SERVER,table,rec.rows[i],INSERT));}
break;case'invalida':sql.push("UPDATE "+ANAGRAFICA_TAB+" SET A_VALIDATO = null WHERE CFISC ='"+cfisc+"'");break;}}
return(sql);},synchronize:function(cfisc,mantieniDichiarazione){this.mantieniDichiarazione=mantieniDichiarazione||false;if(Ext.isEmpty(cfisc)&&Ext.isEmpty(this.arrayCfisc)){this.fireEvent('synchronizeexception','codice fiscale mancante');return false;}
if(!Ext.isArray(cfisc)){cfisc=[cfisc];}
this.arrayCfisc=[];this.confirmed=[];this.not_locked=[];this.errors=[];showLoading('Sincronizzazione in corso',null,null,function(){execSql("SELECT * FROM "+LOCKS_TAB+" WHERE SERIALID = '"+session.serialID+"'",JSONDATAURL,function(response){var responseObj=Ext.decode(response.responseText);var locked=[];var locks=responseObj.rows;log.trace("locks:");for(var i=0,leni=locks.length;i<leni;i++){log.trace("\t",locks[i].CFISC);locked.push(locks[i].CFISC);}
for(var j=0,lenj=cfisc.length;j<lenj;j++){if(locked.indexOf(cfisc[j])==-1){this.not_locked.push(cfisc[j]);}else{this.confirmed.push(cfisc[j]);}}
log.trace("confirmed: "+this.confirmed);log.trace("not_locked: "+this.not_locked);this.checkNuova(0);},function(){this.fireEvent('synchronizeexception','Impossibile verificare lo stato delle dichiarazioni');},this);},this);},getActions:function(listaCfisc){log.trace("arrayCfisc:"+this.confirmed);for(var i=0;i<listaCfisc.length;i++){var currentRec=conn.query(getQuery(SEL_LOCAL_ANAG,[listaCfisc[i]])).rows[0];var singola=true;var dic_cfisc=false;if(!Ext.isEmpty(currentRec.CCFISC)&&(currentRec.ST==2)){listaCfisc.splice(i+1,0,currentRec.CCFISC);singola=false;}
if(currentRec.CONIUGE==1){dic_cfisc=listaCfisc[i-1];singola=false;}
this.arrayCfisc[i]={cfisc:listaCfisc[i],nuovaOffline:(currentRec.PCAT==1),tabelle:[],singola:singola,dicCfisc:dic_cfisc,errors:false};var tabelleRes=this.gearsSysConn.query("SELECT DISTINCT tabella FROM "+this.actTable+" WHERE CFISC = '"+listaCfisc[i]+"'").rows;for(var j=0,lenj=tabelleRes.length;j<lenj;j++){this.arrayCfisc[i].tabelle.push(tabelleRes[j].tabella);}
log.trace(this.arrayCfisc[i]);}
this.syncTable(0,0);},checkNuova:function(cfiscIndex){log.info('checkNuova '+cfiscIndex);if(cfiscIndex<this.not_locked.length){var syncCfisc=this.not_locked[cfiscIndex];var currentRec=conn.query(getQuery(SEL_LOCAL_ANAG,[syncCfisc])).rows[0];if(currentRec.PCAT==1){execSql("SELECT A.CFISC FROM ANAGRAFI A WHERE (A.CFISC = '"+syncCfisc.cfisc+"') UNION SELECT B.CFISC FROM _sys_LOCKS B WHERE (B.CFISC = '"+syncCfisc.cfisc+"')",JSONDATAURL,function(response){var responseObj=Ext.decode(response.responseText);if(responseObj.totalRows==0){conn.exec("UPDATE ANAGRAFI SET PCAT='' WHERE CFISC='"+syncCfisc+"'");this.confirmed.push(syncCfisc);if(currentRec.CCFISC){this.confirmed.push(currentRec.CCFISC);}}else{this.errors.push([syncCfisc,ERROR,"La dichiarazione "+UNI_E+" gi"+UNI_A+" stata creata da un'altro utente."]);this.fireEvent('synccfisc',syncCfisc,this.errors[this.errors.length-1]);}
this.checkNuova(cfiscIndex+1);},function(){this.fireEvent('synchronizeexception',"Errore nella comunicazione con il server.");},this);}else{this.errors.push([syncCfisc,ERROR,'La dichiarazione non risulta utilizzata dall\'utente loggato quindi non '+UNI_E+' stato possibile sincronizzarla.']);this.checkNuova(cfiscIndex+1);}}else{this.getActions(this.confirmed);}},syncTable:function(cfiscIndex,tabIndex){log.info('syncTable '+cfiscIndex+"-"+tabIndex);var syncCfisc=this.arrayCfisc[cfiscIndex];if(tabIndex==0){hideLoading(0,function(){this.progressIncrement=1/syncCfisc.tabelle.length;this.progress=Ext.Msg.progress("Sincronizzazione","Sincronizzazione in corso ("+(cfiscIndex+1)+" di "+this.arrayCfisc.length+")...","0%");},this);}
if(tabIndex<syncCfisc.tabelle.length){var perc=this.progressIncrement*(tabIndex+1)-0.01;this.progress.updateProgress(perc,(perc*100).toFixed(0)+"%","Sincronizzazione in corso ("+(cfiscIndex+1)+" di "+this.arrayCfisc.length+")...");var tabella=syncCfisc.tabelle[tabIndex];this.serverQueries=[];this.serverQueries=this.generateServerQuery(syncCfisc.cfisc,tabella);if(this.serverQueries.length){log.trace("serverQueries:");log.trace(this.serverQueries);this.syncRecord(0,tabIndex,cfiscIndex);}else{this.gearsSysConn.exec("DELETE FROM "+this.actTable+" WHERE CFISC = '"+syncCfisc.cfisc+"' AND tabella = '"+syncCfisc.tabelle[tabIndex]+"'");this.fireEvent('synctable',syncCfisc.cfisc,syncCfisc.tabelle[tabIndex],false);tabIndex++;this.syncTable(cfiscIndex,tabIndex);}}else{if(syncCfisc.errors){this.fireEvent('synccfisc',syncCfisc.cfisc,this.errors[this.errors.length-1]);}else{this.fireEvent('synccfisc',syncCfisc.cfisc,false);}
this.checkFinished(cfiscIndex,true);}},syncRecord:function(sqlIndex,tabIndex,cfiscIndex){var currentCfisc=this.arrayCfisc[cfiscIndex];execSql(this.serverQueries[sqlIndex],WRITEDATAURL,function(response){if(successResultResponse(response)){sqlIndex++;if(sqlIndex<this.serverQueries.length){this.syncRecord(sqlIndex,tabIndex,cfiscIndex);}else{this.gearsSysConn.exec("DELETE FROM "+this.actTable+" WHERE CFISC = '"+currentCfisc.cfisc+"' AND tabella = '"+currentCfisc.tabelle[tabIndex]+"'");this.fireEvent('synctable',currentCfisc.cfisc,currentCfisc.tabelle[tabIndex],false);tabIndex++;this.syncTable(cfiscIndex,tabIndex);}}else{this.fireEvent('synctable',currentCfisc.cfisc,currentCfisc.tabelle[tabIndex],true);if((this.errors.length==0)||(this.errors[this.errors.length-1][0]!=currentCfisc.cfisc)){this.errors.push([currentCfisc.cfisc,ERROR,"Si "+UNI_E+" verificato un'errore durante la sincronizzazione di questa dichiarazione.",unescape(Ext.decode(response.responseText).ErrorMessage)]);this.arrayCfisc.error=true;}
this.syncTable(cfiscIndex,(tabIndex+1));}},function(){this.fireEvent('synchronizeexception',"Errore nella comunicazione con il server.");},this);},checkFinished:function(cfiscIndex,rimuovi){rimuovi=rimuovi||false;log.info('checkFinished '+cfiscIndex+" "+rimuovi);if(rimuovi&&!this.mantieniDichiarazione){var currentCfisc=this.arrayCfisc[cfiscIndex];if(currentCfisc.dicCfisc){if(!this.arrayCfisc[cfiscIndex-1].errors){if(dichiarazione!==undefined&&(currentCfisc.dicCfisc==dichiarazione.cfisc)){chiudiDichiarazione();}
rimuoviDichiarazioneLocale(currentCfisc.dicCfisc);}}
if(currentCfisc.singola){if(dichiarazione!==undefined&&(currentCfisc.cfisc==dichiarazione.cfisc)){chiudiDichiarazione();}
rimuoviDichiarazioneLocale(currentCfisc.cfisc);}}
cfiscIndex++;if(cfiscIndex<this.arrayCfisc.length){this.syncTable(cfiscIndex,0);}else{this.fireEvent('synchronize',this.arrayCfisc,this.errors);}},purgeListeners:function(){Ext.ux.Namirial.data.Synchronizer.superclass.purgeListeners.call(this);this.setListeners();},setListeners:function(){this.on('synchronize',function(){log.info('sinctot');this.progress.updateProgress(1,"100%","Sincronizzazione completa");this.progress.hide();hideLoading();});this.on('synccfisc',function(){log.info('sinccfisc');this.progress.updateProgress(1,"100%","Sincronizzazione completa");this.progress.hide();hideLoading();});this.on('synchronizeexception',function(){this.progress.updateProgress(1,"Errore","Errore nella sincronizzazione");this.progress.hide();hideLoading();});}});

