//------------------------------------------AB HIER NICHTS ÄNDERN--------------------------------------------------------
const versionNr = "15102019-1.5"
const warnColor = warnFarbe ;
const format = "<!DOCTYPE html><html lang=\"de\"><head><title>Putzer</title><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body>";
const htmlTable="<table style=\"color:"+color_in_table+";text-align:left; font-family:"+schriftart+";background-image: linear-gradient(67deg,transparent,"+color_gradient1+");\">";
const htmlReset="<p style=\"color:red;font-family:"+schriftart+";\"><i>!!! ohne Javascript Instanzen !!! kann enabled werden</i></p>"
const htmlHeaders = "style=\"color:"+colorHeadlines+";\""; 
const htmlHeadersDP = "style=\"color:"+colorHeadlinesDP+";\""; 
//  var htmlOhneAnzahl="<p style=\"color:red;font-family:"+schriftart+";\"><i>!!! ohne DatenpunktZählung !!! kann enabled werden</i></p>"
const htmlError="<p style=\"color:red;font-family:"+schriftart+";\"><i>Script hat Fehler - bitte Log checken !!!</i></p>"
var allInstArr=[];
var  instanzArrHelp=[];
const dpPrefix = "javascript."+ instance +".";
var mylogs=false;
var htmlDP=[];
var htmlMSG=[];
var counterAll=0;
var directSearch=false;
var switchOn=false;
var helplogs=true;
var htmlHelper="";
var htmlHelperFile="";
var alarmInstanz1=false;
var unusedDayFactor ;
var unusedDay;
var aliasArr;
var ali;
var monster;
let java;
let instanzAnzahl;
var ohneInstanz;
var endehtmlConst;
var endehtmlDPConst;
var endehtml ;
var endehtmlDP ;
createState(dpPrefix + "ProofingDatapoints.HTMLTable", { name: 'HTMLTable',  type: 'string', read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.ScriptVersion", versionNr,{ name: 'ScriptVersion',  type: 'string', read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.RunScript",false, { name: 'RunScript',  type: 'boolean', role:"switch", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.JavaInstanzCheck", true,{ name: 'JavaInstanzCheck',  type: 'boolean', role:"switch", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.ObjectAnzahlCheck", true,{ name: 'ObjectAnzahlCheck',  type: 'boolean', role:"switch", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.MonsterSearch", false,{ name: 'MonsterSearch',  type: 'boolean', role:"switch", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.ohneInstanzAnzeige", false,{ name: 'ohneInstanzAnzeige',  type: 'boolean', role:"switch", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.OrdnerCheck", "", { name: 'OrdnerCheck',  type: 'string', read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.RunSuccessful", false, { name: 'RunSuccessful',  type: 'boolean', role:"state", read:  true,  write: false,});
createState(dpPrefix + "ProofingDatapoints.LatestChangeDP", false, { name: 'LatestChangeDP',  type: 'boolean', role:"state", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.LatestChangeDP_Factor", 100, { name: 'LatestChangeDP_Factor',  type: 'number', role:"state", read:  true,  write: true,});
createState(dpPrefix + "ProofingDatapoints.CheckAliase", false, { name: 'Check_Alias_0_Ordner',  type: 'boolean', role:"state", read:  true,  write: true,});
//------------------------------------------CHECK INSTANZEN--------------------------------------------------------
async function instanzCount(){
   return new Promise(async (resolve, reject) => {
  var ohneInstanz = getState(dpPrefix + "ProofingDatapoints.ohneInstanzAnzeige").val;
    
   var counter=0; var counter2=0;var counter3=0; 
$('system.adapter.*.alive').each(function(id, i) {
    var ida = id.split('.');
     allInstArr.push(ida[2]+"."+ida[3]);
  if (!ohneInstanz && !directSearch) {
   
   if(!id.includes("vis")){
   
   counter++;
   if (getState(id).val==null) {counter2++; mylog(ida[2]+ida[3]+"--------------------der hier wurde nie gestartet"); 
      htmlDP.push(ida[2]+"."+ida[3]);
      htmlMSG.push("Instanzen ohne Werte");} //else{instanzArr.push(ida[2]+"."+ida[3])}
   if (getState(id).val==false) {counter3++;mylog(ida[2]+ida[3]+"-----------------------der hier ist ausgeschalten"); 
      htmlDP.push(ida[2]+"."+ida[3]);
      htmlMSG.push("nicht aktiviert");} /*else{instanzArr.push(ida[2]+"."+ida[3])}*/
   }}
});
 if (!ohneInstanz) {
mylog("______________________________________________Anzahl Instanzen: " + counter.toString());
htmlDP.push("");
htmlMSG.push("");
htmlDP.push("Anzahl Instanzen");
htmlMSG.push(counter.toString());
mylog("______________________________________________Anzahl gestoppter Instanzen ohne Werte: " + counter2.toString())
htmlDP.push("Instanzen ohne Werte");
htmlMSG.push(counter2.toString());
htmlDP.push("Instanzen nicht aktiviert");
htmlMSG.push(counter3.toString());
 }
 if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in AUSGABE CHECK INSTANZEN :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");}
 
  resolve();
  }); //end promise
}      // end function
//------------------------------------------CHECK TYPE --  ZUORDNUNG--------------------------------------------------------
async function checkTypes(select) {
   return new Promise(async (resolve, reject) => {
       try {
    helplog("bin in check types");
   var counter=0; 
   htmlMSG.push("");
   htmlDP.push("");
  // log(",,,,,,,,,,,,,,liste aliasArr: "+aliasArr.toString(),"error");
   
   var sub= select.substring(select.length-1, select.length); //log("---------: "+sub);//console.log("----------select: "+select);
   mylog(select)
   $(select).each(function (id, i) {
       counter++
     
       
      // var rrr=getState("abs").val
      
    //  console.log("===== falls script nach diesem Eintrag endet, gibt es eine nicht-exisitierende Hauptkategorie - letzte kontrollierte Kategorie: "+ id+" =====");
       //console.log(getObject("abc").common.hasOwnProperty("type"));
    //   if(getObject(id).common.hasOwnProperty("alias")) console.log(id); // TEST ABSTURZ
       
          
   if (!id.includes('scriptEnabled') && !id.includes('scriptProblem')  /*&& getState(id).val !== null && !id.includes('Log-Script')  && !id.includes('Ereignisliste') && !id.includes('GETPROCESS')*/ ){
       //console.log("===============id vor null - kein value zu:  "+id);
      //console.log("status0-checkType");
       //if (getState(id).val==null) console.log("===============nullwert - kein value zu:  "+id);
      
      //console.log("status1-checkType"); 
      //console.log(JSON.stringify(getObject(id).common));
       if (!JSON.stringify(getObject(id)).includes("type") && !JSON.stringify(getObject(id)).includes("name") /*&& !JSON.stringify(getObject(id)).includes("meta")*/ ) {
      //console.log("===============id nach stringify - kein value zu:  "+id);
            var valType = typeof getState(id).val;
             htmlDP.push(id+": "+valType);
             htmlMSG.push("<b>missing DP-OBEJCT !!</b>" );}
       
        else{ //console.log("status2-checkType");
            var dpType = getObject(id).common.type;
            var valType = typeof getState(id).val;
            if(getObject(id).common.type ==null || getObject(id).common.type == undefined || getObject(id).common.type =="") {
                 //console.log("shit happens","error");
                 htmlDP.push(id);
                 htmlMSG.push("-col-<b>ACHTUNG common.type fehlt</b>");                  
                 } 
            else {
            let typesIOhelp=false;                     // VERGLEICH/PRÜFUNG MIT ALLEN TYPES
            for (var i =0; i<typesIO.length;i++) {
                var re = new RegExp("\\b" + typesIO[i] + "\\b", "g");
               // console.log(dpType.match(re)+" ID : "+id+" i=: "+i.toString() + " wert : "+typesIO[i]);
                if (dpType.match(re) && i < typesIO.length) {typesIOhelp=true;break;} else {typesIOhelp=false; }}
                if (!typesIOhelp) {//console.log("========================hier fehler mit type nicht in constante:  " +id);       
                                   htmlDP.push(id);
                                   htmlMSG.push("-col-<b>ACHTUNG common.type falsch: "+dpType+"</b>");}}
             
            if (getState(id).val !== null){          // ANZEIGE ALLER DATENPUNKTE MIT STATE=null
              if(dpType != "mixed" ) {
              if(dpType !== valType && !(dpType == 'array' && valType == 'object' &&  dpType == 'meta.user') /*&& !(dpType =='text' && valType=='string') && !(dpType =='string' && valType=='text')*/ ) {
                 mylog(id + ': Datenpunkttyp: ' + dpType + ', Wert: ' + valType);
                 htmlDP.push(id+": "+valType);
                 htmlMSG.push(dpType );}
             
                 }//end of check common.type and value-type 
           } //end of mixed
       
      } // end of check object includes name and type
   }//ende if scriptenabled
   });
   htmlDP.push("<i>ID + IST-WERT</i>");
   htmlMSG.push("<i>SOLL-WERT</i>");
   htmlDP.push("-col-<b>geprüfte Instanz</b>");
   htmlMSG.push("-col-<i><b>"+select+"</b></i>");
   if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in AUSGABE CHECK WERTE :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");}
   helplog("fertg in checkType mit: "+select+ "und " + counter.toString()+ " Durchläufen")
     resolve();
      } catch (e) {console.log("------------ERROR: "+e ); reject(); return alarmInstanz1=true}
  }); //end promise
}      //end function
//------------------------------------------CHECK  WERTE--------------------------------------------------------
async function checkWerte(select) {
   return new Promise(async (resolve, reject) => {
       try{
   helplog("bin in check Werte");
   var counter=0; 
   var jetzt=new Date().getTime();
   var error1;
   mylog(select);
   $(select).each(function (id, i) {
       counter++
        error1=id;
     //console.log(getObject("abc").common.hasOwnProperty("type"));   // TEST ABSTURZ
     // console.log("statusalias");
     
   if (!id.includes('scriptEnabled') && !id.includes('scriptProblem') /*&& !id.includes('alias.0')  )  && !id.includes('Ereignisliste') && !id.includes('GETPROCESS')*/ ){
      //var dpType = getObject(id).common.type;
       
     
            if (!JSON.stringify(getObject(id)).includes("type") && !JSON.stringify(getObject(id)).includes("name") ) { //CHECK MISSING OBJECT))
             try{
             valType = typeof getState(id).val;
             } catch (e) {console.log("------------ERROR: "+e + "bei id: " + id); return alarmInstanz1=true}
             htmlDP.push(id+": "+valType);
             htmlMSG.push("<b>missing DP-OBEJCT !!</b>" );}
             else {
        //              console.log("status0");
                   var valType =  getState(id).val;
                   // if(dpType != "mixed" ) {}
          //          console.log("status1");
                  if(valType === null) {mylog(id + ': Datenpunkttyp: ' /*+ dpType */+ ", Wert: "+valType);
                        htmlDP.push(id);
                        var ddd = jetzt-getObject(id).ts; //getState(id).ts 
                       // if (ddd == NaN) log(ddd.toString(),"error");
                         //log(getState(id).ts.toString(),"error");
                        
                        //if(ddd==undefined)
                        htmlMSG.push("not used & created at: " + Math.floor((ddd)/1000/60/60/24)+"d "+Math.floor((ddd)/1000/60/60 %24)+"h "+Math.floor((ddd)/1000/60 %60)+"m");
                        } 
                   else {  if (unusedDay){//console.log(  (jetzt - (86400000 * unusedDayFactor))-getObject(id).ts + id + getState(id).ts );  
                          var ddd = jetzt-getState(id).ts;
                          if ( (jetzt - (86400000 * unusedDayFactor)) - getState(id).ts > 0 ){
                             htmlDP.push(id);
                             htmlMSG.push("lastChange over "+ unusedDayFactor +" days");
                             htmlDP.push("");
                             htmlMSG.push("created: "+ Math.floor((ddd)/1000/60/60/24)+"d "+Math.floor((ddd)/1000/60/60 %24)+"h "+Math.floor((ddd)/1000/60 %60)+"m");                              
                             }}} 
            //       console.log("status2");
                   if(getObject(id).common.hasOwnProperty("states") /*&& JSON.stringify(getObject(id).common.states)!=null && JSON.stringify(getObject(id).common.states)!=undefined */){
                           // console.log("======2=============no type: "+id +"object: "+JSON.stringify(getObject(id).common.states));
                           //console.log("der hier: " +id);
                           try{
                               var helpStates= Object.keys(getObject(id).common.states);
                           } catch (e) {console.log("------------ERROR: "+e + "bei id: " + id); extendObject(id, {common: {states:{"0":"script"}}})}
                   var helpType= getObject(id).common.type;
                   //  console.log(helpType);//console.log(helpStates.toString()); // console.log(helpStates[0] + helpStates[1] );
                   if (helpType=="number" || helpType=="boolean") {
                       var alarmString=false;var alarmString2=false;
                       for (var i=0;  i  < helpStates.length ;i++){
                           //  console.log( helpStates[i]);
                           mylog(isNaN(helpStates[i]).toString())  ;
                           if (isNaN(helpStates[i]) && helpType=="number") alarmString=true; //type number - stehen da nummern drin
                           var helpTypeBool= helpStates[i].toString()  + helpType;
                           if  (helpType=="boolean") {if (helpTypeBool !="falseboolean" && helpTypeBool != "trueboolean")  alarmString2=true;} //type boolean - stehen da booleans
                       }
                       if (alarmString){  htmlDP.push(id);
                                      htmlMSG.push("-col-<b>ACHTUNG Multstate must be number</b>")}
                       if (alarmString2){ htmlDP.push(id);
                                      htmlMSG.push("-col-<b>ACHTUNG Multstate must be boolean</b>")}
                   } else {htmlDP.push(id);
                           htmlMSG.push("-col-<b>ACHTUNG Multstate wrong Def.</b>")}
        
                   } //ende states check
                  // var ddd = (new Date().getTime()-864000000) getObject(id).ts;
                   
                                                        /*   console.log("_____________________bin in type check groß:länge types:  "+ typesIO.length );
                             if(getObject(id).common.hasOwnProperty("type")){
                                   let typesIOhelp=false; 
                                   for (var i =0; i<typesIO.length;i++) {
                                       console.log(getObject(id).common.type.includes(typesIO[i])+" ID : "+id+" i=: "+i.toString() + " wert : "+typesIO[i]);
                                     
                                       if (getObject(id).common.type.includes(typesIO[i]) && i < typesIO.length) {typesIOhelp=true;break;} else {typesIOhelp=false; }}
                             if (!typesIOhelp) {console.log("========================hier fehler mit type nicht in constante:  " +id);       
                                                htmlDP.push(id);
                                                htmlMSG.push("-col-<b>ACHTUNG common.type falsch - "+getObject(id).common.type+"</b>");}
                                               
                             } else {mylog("ok in type constante  :" + id);}*/
                             //ende alle typen check    
   } //ende check missing object
   } // ende script enabled check
   }); // ende selct.each
    if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in ANZAHL AUSGABE CHECK WERTE :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");}
    helplog("bin raus aus check Werte bei :"+ select);
    resolve("ok");
     } catch (e) {console.log("------------ERROR: "+e ); reject(error1); return error1}
  }); //end promise
}      //end function
//---------------------------------------------------------------------------------------------------------------------
function mylog(message) {
  if(mylogs)
      console.log(message);
}function helplog(message) {
  if(helplogs)
      console.log(message);
}
//------------------------------------------Zähle Objecte der  INSTANZEN--------------------------------------------------------
async function countDP(idb){
   mylog("bin richtig in count");
   var counter4=0;
   $(idb+".*").each(function(id, i) {
   counter4++; })
mylog(idb+counter4);
htmlDP.unshift(idb);
htmlMSG.unshift(counter4.toString());
counterAll=counterAll+counter4;
if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in AUSGABE ZÄHLEN INSTANZEN :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");}
mylog("bin raus aus count");
}
//----------------------------------------------Direct Suchen
on({id:dpPrefix + "ProofingDatapoints.OrdnerCheck", ack: false, change: "any"}, function (obj) {
 
    directSearch=true;
     instanzArrHelp=[];
    setState(dpPrefix + "ProofingDatapoints.RunScript",true);
   
   
    });
//-----------------------------------------------ALIAS CHECK------------------------------------------------
async function checkAlias() {
   return new Promise(async (resolve, reject) => {
       try{
   helplog("bin in check aliase");
   let counter=0; 
   var jetzt=new Date().getTime();
   var aliasArrAlarm
   aliasArr=[];
   var aliasArrOrg=[];
       for(var l=0;l<instanzArr.length;l++)  { //für eigene datenpunkte
               allInstArr.push(instanzArr[l]);
       }
    $("alias.0.*").each(function (id, i) {
    if(id.includes("alias.0") ) {
        if( JSON.stringify(getObject(id).common).includes("alias")) {      
        //   var helpAlias= Object.keys(getObject(id).common.alias);                              // erstellt ALIAS ARRAY
       // log("_!_!_!_!_!__!_!_!_!_!_!_!_ "+id  + "hat ALIAS mit :"+ getObject(id).common.alias.id ,"error");
        aliasArr.push(getObject(id).common.alias.id);
        aliasArrOrg.push(getObject(id)._id);
       }}
        }); // ende alias finden 
              
          
     //log("bin in array " + "länge: "+ aliasArr.length+"--"  + " ganz : " +aliasArr.toString(),"error");
    
    /*  $("controll-own.0.*").each(function (id, i) {
                 
                   if (id=="controll-own.0.AAATEST.AARolladen4") log("HIER IT ES1"+ JSON.stringify(getObject(id))+" counter : " + counter);  
                  log("HIER IT ES1"+ id +" counter : " + counter);});*/
              
              aliasArrAlarm=false; 
            //  log(allInstArr.toString());
            for(var l=0;l<allInstArr.length;l++)  {
              $(allInstArr[l]+".*").each(function (id, i) {
                  counter++;
                  // if (id=="controll-own.0.AAATEST.AARolladen44") log("HIER IT ES"+ JSON.stringify(getObject(id))+" counter : " + counter);
                          // for(let index in aliasArr){
                  for (var h=0; h<aliasArr.length;h++){
                           // log(allInstArr[l]+"---:---"+id,"error");
                  if (id ==aliasArr[h]  && aliasArr[h] != "found" ) { htmlDP.push(aliasArrOrg[h]); htmlMSG.push("ALIAS: ok : "+id); /*log("--------erfolgreich ID: "+id+" ARRAY:  "+aliasArr[h])*/; aliasArr[h] = "found"; aliasArrAlarm=false;   } 
                  } 
                 // aliasArrAlarm=false;
                 //for (var h=0; h<aliasArr.length;h++){ if (aliasArr[h] == "found") {aliasArrAlarm=true;}}
              }); // ende allInstArr
                 } //end of  selct.each 
                 for (var h=0; h<aliasArr.length;h++)
                      { if (aliasArr[h]!="found") {htmlDP.push(aliasArrOrg[h]);
                                                   htmlMSG.push("-col-<b>ACHTUNG wrong DP assignment: </b>");}}
              //    log(aliasArr.toString(),"error");
                                                                       //             if(!aliasArrAlarm && parseInt(index) > aliasArr.length-1){break;}
               
         /*      if (aliasArrAlarm) {console.log("========================hier fehler mit a l i a s:  " );       
                                   htmlDP.push(aliasArr[index]);
                                   htmlMSG.push("-col-<b>ACHTUNG missing ALIAS: </b>");}
               else { htmlDP.push(aliasArr[index]);
                      htmlMSG.push("ALIAS: ok")}
                       if(!aliasArrAlarm && parseInt(index) > aliasArr.length-1){break;}*/
                     
                                          
         
         /* 
           if(select.includes("alias.0") ) {aliasArrAlarm=false;}
              
               for (var i =0; i<aliasArr.length;i++) {
                    var re = new RegExp("\\b" + aliasArr[i] + "\\b", "g");
               // console.log(dpType.match(re)+" ID : "+id+" i=: "+i.toString() + " wert : "+typesIO[i]);
                if (dpType.match(re) && i < aliasArr.length) {aliasArrAlarm=true;break;} else {aliasArrAlarm=false; }}
                if (!aliasArrAlarm) {consolelog("========================hier fehler mit a l i a s:  " +id);       
                                   htmlDP.push(id);
                                   htmlMSG.push("-col-<b>ACHTUNG missing ALIAS: </b>");
               }
                 
       } */
   htmlDP.push("<i>ALIAS DP ASSIGNMENT</i>");
   htmlMSG.push("<i>ALIAS STATUS</i>");
   htmlDP.push("-col-<b>geprüftes Alias</b>");
   htmlMSG.push("-col-<i><b>Anzahl: "+aliasArr.length+"</b></i>");
   htmlDP.push("");
   htmlMSG.push("");
    if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in ANZAHL AUSGABE CHECK ALIAS :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");}
    helplog("bin raus aus check aliase");
    resolve();
     } catch (e) {console.log("------------ERROR: "+e ); reject(); return alarmInstanz1=true}
  }); //end promise
}      //end function
async function calmDown(howLong){
   let promise = new Promise((res, rej) => {
       setTimeout(() => res("Now it's done!"), howLong)
   });
   // wait until the promise returns us a value
   let result = await promise; 
 
   // "Now it's done!"
   log(result,"error"); 
   }
   /*
};
firstAsync();
 var timeout = setTimeout(function () {
     log("pause");
}, 3000);}*/
//-------------------------------------------------write stuff----------------------------------------------
async function writeStuff() {
//ab hier geht es um die ausgabe
if (htmlDP.length != htmlMSG.length) {console.log("-------- !!! FEHLER in ANZAHL DATENAUSGABE :  "+ "AnzahlDP: "+htmlDP.length+" AnzahlMSG: "+htmlMSG.length,"error");} 
 else {
 //console.log(htmlMSG.length+"--"+htmlDP.length)
for(var i= htmlDP.length-1; i>-1; i--) {
   //console.log(htmlDP[i]+"anerer :"+htmlMSG[i]);
     //  if (htmlMSG[i].includes("-col-")) console.log(htmlMSG[i]);
       let htmlDPVis; let htmlDPFile;let htmlMSGVis;let htmlMSGFile;
       if(htmlDP[i].includes("-col-")) {htmlDPVis=htmlDP[i].replace("-col-", (htmlHeadersDP+">"));  htmlDPVis=" "+htmlDPVis } else {htmlDPVis=">"+htmlDP[i]}
       if(htmlMSG[i].includes("-col-")) {htmlMSGVis=htmlMSG[i].replace("-col-", (htmlHeadersDP+">"));htmlMSGVis=" "+htmlMSGVis } else {htmlMSGVis=">"+htmlMSG[i]}
       htmlHelper= htmlHelper+"<tr><td"+htmlDPVis+"  </td><td"+htmlMSGVis+"  </td></tr>"
    //  if(htmlDP[i].includes("-col-")) {htmlDP[i]=htmlDP[i].replace("-col-", (htmlHeaders+">")); htmlDPFile=htmlDP[i]; htmlDPFile= " "+htmlDPFile ; } else {htmlDPFile=">"+htmlDP[i]}
       if(htmlDP[i].includes("-col-")) {htmlDPFile=htmlDP[i].replace("-col-", (htmlHeaders+">"));  htmlDPFile= " "+htmlDPFile ; } else {htmlDPFile=">"+htmlDP[i]}
       if(htmlMSG[i].includes("-col-")) {htmlMSGFile=htmlMSG[i].replace("-col-", (htmlHeaders+">")); htmlMSGFile=" "+htmlMSGFile; } else {htmlMSGFile=">"+htmlMSG[i]}    
       htmlHelperFile= htmlHelperFile+"<tr><td"+htmlDPFile+"  </td><td"+htmlMSGFile+"  </td></tr>"
}
      endehtml=endehtmlConst;
      endehtmlDP=endehtmlDPConst;                       
    
   if (monster){endehtml="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! Monster Suche wird automatisch  deaktiviert !!!</i></p>"+endehtml;
             endehtmlDP="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! ACHTUNG: SYSTEM WIRD BELASTET !!! </br></br>!!! Monster Suche wird automatisch  deaktiviert !!! </br></br> BERICHT/AUSWERTUNG NUR ÜBER WEBSEITE</i></p>"+endehtmlDP;}
   if (!instanzAnzahl){endehtml="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! Auswertung ohne DatenpunktZählung !!! kann enabled werden</i></p>"+endehtml;
             endehtmlDP="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! Auswertung ohne DatenpunktZählung !!! kann enabled werden</i></p>"+endehtmlDP;}
   if (!java){ endehtml="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! Auswertung ohne Javascript Instanzen !!! kann enabled werden</i></p>"+endehtml;
             endehtmlDP="<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\"><i>!!! Auswertung ohne Javascript Instanzen !!! kann enabled werden</i></p>"+endehtmlDP;}
   
   if(!monster) { setStateDelayed(dpPrefix + "ProofingDatapoints.HTMLTable",endehtmlDP+"<table>"+htmlHelper,900);} else{setStateDelayed(dpPrefix + "ProofingDatapoints.HTMLTable",endehtmlDP,900);}
  
   mylog("================================schreibe file")  ; 
   writeFile(null, "/ProofingDatapoints/htmlputz.html" ,format+endehtml+htmlTable+htmlHelperFile+"</table></body>", function (error) { mylog('file written'); });
  // endehtml=endehtmlConst;
  // endehtmlDP=endehtmlDPConst;
   setState(dpPrefix + "ProofingDatapoints.MonsterSearch",false);  //setzt monstersearch zurück
   directSearch=false;
    setState(dpPrefix + "ProofingDatapoints.RunSuccessful",true); 
    } //ende else bei fehler im array zur ausgabe
    }
//-----------------------------------------------SCHALTER MAIN------------------------------------------------
on({id:dpPrefix + "ProofingDatapoints.RunScript", ack: false, val: true}, function (obj) { 
  mainScript();
});
async function mainScript(){
   setState(dpPrefix + "ProofingDatapoints.RunSuccessful",false); 
    java= getState(dpPrefix + "ProofingDatapoints.JavaInstanzCheck").val;
    instanzAnzahl= getState(dpPrefix + "ProofingDatapoints.ObjectAnzahlCheck").val;
   monster= getState(dpPrefix + "ProofingDatapoints.MonsterSearch").val;
    ohneInstanz = getState(dpPrefix + "ProofingDatapoints.ohneInstanzAnzeige").val;
   unusedDayFactor = getState(dpPrefix + "ProofingDatapoints.LatestChangeDP_Factor").val;
   ali = getState(dpPrefix + "ProofingDatapoints.CheckAliase").val;
   unusedDay = getState(dpPrefix + "ProofingDatapoints.LatestChangeDP").val;
    endehtmlConst=   "<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\">Letztes File Update: "+formatDate(getDateObject((parseFloat((new Date().getTime())))), "SS:mm:ss")+"</p>";
    endehtmlDPConst=   "<p style=\"color:"+warnColor+"; font-family:"+schriftart+";\">Letztes Table Update: "+formatDate(getDateObject((parseFloat((new Date().getTime())))), "SS:mm:ss")+"</p>";
   setState(dpPrefix + "ProofingDatapoints.ScriptVersion",versionNr);
   htmlHelper="";
   htmlHelperFile="";
   counterAll=0;
   instanzArrHelp=[];
   allInstArr=[];
   htmlDP=[];
   htmlMSG=[];
   aliasArr=[];
   setState(dpPrefix + "ProofingDatapoints.HTMLTable",htmlReset+endehtml+htmlError);
   setStateDelayed(dpPrefix + "ProofingDatapoints.RunScript",false,2500);    
   writeFile(null, "/ProofingDatapoints/htmlputz.html" ,htmlReset+endehtml+htmlError+"</body>", function (error) {mylog('file written'); });
log('_______________________ starte Instanz Count');
await instanzCount();   
await writeStuff();
if (true) await calmDown(1000);
                                                                                //überprüft instanzen und stellt allInstArr her
htmlDP.push("-col-<b>INSTANZ INFO</b>"); htmlMSG.push(""); htmlDP.push(""); htmlMSG.push("");
log(instanzArr.length+"==================="+instanzArr.toString());
if (monster) {instanzArrHelp=allInstArr;} else {instanzArrHelp=instanzArr}  //ACHTUNG MONSTERSEARCH
if (directSearch) {instanzArrHelp=[]; instanzArrHelp.push(getState(dpPrefix + "ProofingDatapoints.OrdnerCheck").val);}
log('_______________________ starte durch array Instanzen');
for(let name in instanzArrHelp){
   if (monster) await calmDown(150);
   await checkWerte(instanzArrHelp[name]+".*").then( message => {console.log("Funktion Check Werte erfolgreich","error");  });
   await writeStuff();
   
   if (true) await calmDown(1000);
                                                           //checkt alle werte in intanzArr
    mylog("!!!!!!!!!!!!!!!!!!!!:  "+instanzArrHelp[name]);   } 
    if (instanzAnzahl){
          htmlDP.unshift(""); htmlMSG.unshift("");htmlDP.unshift("<b>OBJECTE IN INSTANZ</b>"); htmlMSG.unshift("Anzahl"); 
           
          for(let name in instanzArrHelp){
            countDP(instanzArrHelp[name]);mylog("bin in zählen");}
            if (java && !monster) countDP("javascript")
          htmlDP.unshift("-col-<b>GESAMT GEPRÜFTE OBJECTE IN INSTANZEN</b>"); htmlMSG.unshift("-col-<b>"+counterAll.toString()+"</b>"); 
          
          }
          mylog("=============: "+counterAll);
           
 if (monster) await calmDown(2000);         
if (java && !monster && !ohneInstanz && !directSearch) await checkWerte('javascript.*').catch().then();                 //checkt alle javainstanzen
log("STOPPE SCRIPT");
//stopScript();
 htmlDP.push("-col-<b>ID's OHNE WERT:</b>");
 htmlMSG.push("");
log('_______________________ starte durch array Type Check');
for(let name in instanzArrHelp){
   if (monster) await calmDown(150);
   await checkTypes(instanzArrHelp[name]+".*").catch().then();
   mylog("!!!!!!!!!!!!!!!!!!!!:  "+instanzArrHelp[name])};
     htmlDP.push("");
     htmlMSG.push("");
     htmlDP.push("-col-<b>IDs MIT FALSCHEN TYPE:</b>");
     htmlMSG.push("");
 if (java && !monster && !ohneInstanz && !directSearch ) await checkTypes('javascript.*').catch().then();          //checkt java instanz dp auf type
  //log(allInstArr.toString(),"error");
  if(ali) {log('_______________________ starte durch array Type Check');
          await checkAlias();}
 log('_______________________ starte durch array Type Check');
  writeStuff();
}
const typesIO = ["boolean", "number", "string", "object", "array", "mixed", "sensor.window", "sensor.door", "sensor.alarm", "sensor.alarm.flood", "sensor.alarm.fire", "sensor.alarm.secure", "sensor.alarm.flood", "sensor.alarm.power", "sensor.alarm.secure", "sensor.door", "sensor.light", "sensor.lock", "sensor.motion", "sensor.rain", "sensor.noise", "sensor.rain", "sensor.window", "button", "button.long", "button.stop", "button.start", "button.open.door", "button.open.window", "button.mode", "button.mode.auto", "button.mode.manual", "button.mode.silent", "button.open.door", "button.open.window", "button.start", "button.stop", "value", "value.window", "value.temperature", "value.humidity", "value.battery", "value.blind", "value.brightness", "value.min", "value.max", "value.current", "value.curtain", "value.default", "value.battery", "value.valve", "value.time", "value.direction", "value.distance", "value.distance.visibility", "value.gps", "value.gps.elevation", "value.gps.latitude", "value.gps.longitude", "value.humidity", "value.interval", "value.gps.longitude", "value.gps.latitude", "value.gps.elevation", "value.gps", "value.power.consumption", "value.direction", "value.curtain", "value.blind", "value.tilt", "value.lock", "value.speed", "value.max", "value.min", "value.power.consumption", "value.pressure", "value.distance", "value.distance.visibility", "value.severity", "value.warning", "value.sun.elevation", "value.speed", "value.sun.azimuth", "value.sun.elevation", "value.temperature", "value.tilt", "value.time", "value.valve", "value.voltage", "value.current", "value.warning", "value.window", "indicator", "indicator.working", "indicator.reachable", "indicator.connected", "indicator.maintenance", "indicator.maintenance.lowbat", "indicator.maintenance.unreach", "indicator.maintenance.alarm", "indicator.lowbat", "indicator.alarm", "indicator.alarm.fire", "indicator.alarm.flood", "indicator.alarm.secure", "indicator.connected", "indicator.lowbat", "indicator.maintenance", "indicator.maintenance.alarm", "indicator.maintenance.lowbat", "indicator.maintenance.unreach", "indicator.reachable", "indicator.working", "level", "level.co2", "level.dimmer", "level.blind", "level.temperature", "level.valve", "level.color.red", "level.color.green", "level.co2", "level.color.blue", "level.color.white", "level.color.green", "level.color.hue", "level.color.saturation", "level.color.rgb", "level.color.luminance", "level.color.red", "level.color.rgb", "level.color.saturation", "level.color.temperature", "level.color.white", "level.curtain", "level.dimmer", "level.temperature", "level.tilt", "level.timer", "level.timer.sleep", "level.valve", "level.volume", "level.volume.group", "level.curtain", "level.tilt", "switch", "switch.lock", "switch.lock.door", "switch.lock.window", "switch.boost", "switch.light", "switch.comfort", "switch.enable", "switch.power", "switch.light", "switch.lock", "switch.lock.door", "switch.lock.window", "switch.mode.*", "switch.mode.auto", "switch.mode.color", "switch.mode.manual", "switch.mode.silent", "switch.mode.moonlight", "switch.mode.color", "switch.mode.silent", "switch.power", "button.stop", "button.play", "button.fastforward", "button.fastreverse", "button.forward", "button.next", "button.prev", "button.pause", "switch.pause", "button.forward", "button.play", "button.prev", "button.reverse", "button.fastforward", "button.fastreverse", "button.volume.up", "button.stop", "button.volume.down", "media.seek", "media.mode.shuffle", "media.mode.repeat", "media.state", "media.artist", "button.volume.up", "level.bass", "level.treble", "media.add", "media.album", "media.title", "media.title.next", "media.artist", "media.bitrate", "media.broadcastDate", "media.clear", "media.content", "media.cover", "media.cover.big", "media.cover.small", "media.duration.text", "media.date", "media.duration", "media.elapsed.text", "media.duration.text", "media.elapsed", "media.broadcastDate", "media.mute", "media.season", "media.elapsed.text", "media.episode", "media.mute.group", "media.tts", "media.bitrate", "media.genre", "media.date", "media.track", "media.input", "media.jump", "media.link", "media.mode.repeat", "media.mode.shuffle", "media.mute", "media.mute.group", "media.playid", "media.add", "media.clear", "media.playlist", "media.season", "media.seek", "media.state", "media.title", "media.title.next", "media.track", "media.tts", "media.url", "media.url.announcement", "media.jump", "media.content", "media.link", "media.input", "level.bass", "level.treble", "switch.pause", "switch.power.zone", "value.temperature", "value.temperature.windchill", "value.temperature.dewpoint", "value.temperature.feelslike", "value.temperature.min", "value.temperature.max", "value.humidity", "value.humidity.min", "value.humidity.max", "value.speed.wind", "value.speed.max.wind", "value.speed.min.wind", "value.speed.wind.gust", "value.direction.wind", "value.direction.max.wind", "value.direction.min.wind", "weather.direction.wind", "date", "date.forecast.1", "date.sunrise", "date.sunset", "dayofweek", "location", "weather.icon", "weather.icon.wind", "weather.icon.name", "weather.state", "value.clouds", "value.direction.max.wind", "value.direction.min.wind", "value.direction.wind", "value.direction.wind.forecast.0", "value.direction.wind.forecast.1", "value.humidity", "value.humidity.max", "value.humidity.min", "value.precipitation", "value.precipitation.day.forecast.0", "value.precipitation.forecast.0", "value.precipitation.forecast.0", "value.precipitation.forecast.1", "value.precipitation.forecast.1", "value.precipitation.hour", "value.precipitation.night.forecast.0", "value.precipitation.today", "value.pressure.forecast.0", "value.pressure.forecast.1", "value.radiation", "value.uv", "value.clouds", "value.rain", "value.rain.hour", "value.rain.today", "value.snow", "value.snow.hour", "value.snow.today", "value.snowline", "value.speed.max.wind", "value.speed.min.wind", "value.speed.wind", "value.speed.wind.forecast.0", "value.speed.wind.forecast.1", "value.speed.wind.gust", "value.temperature", "value.temperature.dewpoint", "value.temperature.feelslike", "value.temperature.max", "value.temperature.max.forecast.0", "value.temperature.max.forecast.1", "value.temperature.min", "value.temperature.min.forecast.0", "value.temperature.min.forecast.1", "value.temperature.windchill", "value.uv", "weather.chart.url", "weather.chart.url.forecast", "weather.direction.wind", "weather.direction.wind.forecast.0", "weather.html", "weather.title", "weather.title.short", "weather.type", "weather.icon", "weather.icon.forecast.1", "weather.icon.name", "weather.icon.wind", "weather.json", "value.speed.wind.forecast.0", "weather.state", "weather.state.forecast.0", "value.direction.wind.forecast.0", "weather.direction.wind.forecast.0", "value.pressure.forecast.0", "value.temperature.min.forecast.0", "value.temperature.max.forecast.0", "value.precipitation.forecast.0", "value.precipitation.forecast.0", "weather.state.forecast.1", "weather.title", "weather.title.forecast.0", "value.precipitation.day.forecast.0", "value.precipitation.night.forecast.0", "weather.title.short", "weather.type", "date.forecast.1", "weather.icon.forecast.1", "weather.state.forecast.1", "value.temperature.min.forecast.1", "value.temperature.max.forecast.1", "value.precipitation.forecast.1", "value.precipitation.forecast.1", "value.direction.wind.forecast.1", "value.speed.wind.forecast.1", "value.pressure.forecast.1", "date.end", "date.start", "info.address", "info.display", "info.ip", "info.mac", "info.name", "info.address", "info.port", "info.standby", "info.status", "info.display", "date.start", "date.end", "text.phone", "url.icon", "url.cam", "url.audio", "url.blank", "url.cam", "url.icon", "url.same", "url.audio", "text.phone", "adapter.messagebox", "adapter.wakeup",]