function changeValueType(event){
    dropdown = event.currentTarget;
    type = dropdown.options[dropdown.selectedIndex].dataset.type;
    id = dropdown.id.match(/\d+$/);
    if(dropdown.id.search("act") > -1){
      opBtnID = "btnActOperator"+id;
      valBlockID = "actValBlock"+id;
      valElemID = "actValue"+id;
    }else{
      opBtnID = "btnOperator"+id;
      valBlockID ="valBlock"+id;
      valElemID = "threshold"+id;
    }
    if(type =="hidden"){
      document.getElementById(opBtnID).hidden = true;
      document.getElementById(valBlockID).hidden = true;
    }else{
      document.getElementById(opBtnID).hidden = false;
      document.getElementById(valBlockID).hidden = false;
      document.getElementById(valElemID).type = type;
    }
  }

  function fillSensorDD(ID){
    var elem = document.getElementById("sensorSelect"+ID);
    fetch("./ajax/fillSensorDD.php", {
      method: 'GET',
      headers: {
        'X-Requested-From-Modal': 'a',
        'Requested-With-Ajax': 'ajax'
      }
    })
      .then(response => response.text())
      .then(html => {
        elem.innerHTML = html;
        elem.addEventListener("change", arrangeSensorInputs);
        document.getElementById("paramSelect"+ID).addEventListener("change", changeValueType);
        elem.dispatchEvent(new Event('change'));
      })
      .catch(error => {
        elem.innerHTML = "";
      });
  }

  function fillActorDD(ID){
    var elem = document.getElementById("actorSelect"+ID);
    fetch("./ajax/fillActorDD.php", {
      method: 'GET',
      headers: {
        'X-Requested-From-Modal': 'a',
        'Requested-With-Ajax': 'ajax'
      }
    })
      .then(response => response.text())
      .then(html => {
        elem.innerHTML = html;
        elem.addEventListener("change", arrangeActorInputs);
        document.getElementById("actParamSelect"+ID).addEventListener("change", changeValueType);
        document.getElementById("actorSelect"+ID).dispatchEvent(new Event('change'));
      })
      .catch(error => {
        elem.innerHTML = "";
      });
  }

  function changeAllIDs (parentNode, newID) {
    for (var i = 0; i < parentNode.childNodes.length; i++) {
      var child = parentNode.childNodes[i];
      changeAllIDs(child, newID);
    }
    if(parentNode.id){
      parentNode.id = parentNode.id.replace(/\d+$/, newID);
    }
    if(parentNode.dataset !== undefined){
      if(parentNode.dataset.delid)
        parentNode.dataset.delid = parentNode.dataset.delid.replace(/\d+$/, newID);
    }
  }

  function delAutoEntry(event){
    ID = event.currentTarget.dataset.delid;
    document.getElementById(ID).remove();
    ID = ID.replace(/\d+$/, function(n){ return ++n });
    while(sensor= document.getElementById(ID)){
      changeAllIDs(sensor, ID.match(/\d+$/)-1);
      ID = ID.replace(/\d+$/, function(n){ return ++n });
    }
  }
  function addSensor(event){
    var t = document.getElementById('sensorsList').children;
    //get the second last element (ignore "add" button)
    nextID = Number(t[t.length-1].id.replace("sensorSettings","")) + 1;
    var div = document.createElement('div');
    div.className = "input-group mt-3";
    div.id = "sensorSettings"+String(nextID);
    div.innerHTML = `<button class='btn btn-outline-secondary' type='button' id='btnLogic${nextID}' name='btnLogic${nextID}' data-tglstates='["und","oder"]' >und</button>
	  		<div class="form-floating">
        		<select class="form-select" id="sensorSelect${nextID}" name="sensorSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Sensor</label>
			</div>
			<div class="form-floating" id="paramBlock${nextID}">
				<select class="form-select" id="paramSelect${nextID}" name="paramSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Messwert</label>
			</div>
			<button class="btn btn-outline-secondary " type="button" id="btnOperator${nextID}" name="btnOperator${nextID}">&gt;</button>
			<div class="form-floating" id="valBlock${nextID}">
				<input  type="number" class="form-control" id="threshold${nextID}" name="threshold${nextID}" placeholder="0" value="0"></input>
				<label>Wert/Schwelle</label>
			</div>
      <button class='btn btn-outline-danger' type='button' id='btnDel${nextID}' data-delid="sensorSettings${nextID}" onclick="delAutoEntry(event)"><i class="bi bi-trash3"></i></button>
		</div>`;
    document.getElementById("sensorsList").appendChild(div);
    fillSensorDD(nextID);
  }

  function addActor(event){
    var t = document.getElementById('actorsList').children;
    //get the second last element (ignore "add" button)
    nextID = Number(t[t.length-1].id.replace("actorSettings","")) + 1;
    var div = document.createElement('div');
    div.className = "input-group mt-3";
    div.id = "actorSettings"+String(nextID);
    div.innerHTML = `<div class="form-floating">
        		<select class="form-select" id="actorSelect${nextID}" name="actorSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Aktor</label>
			</div>
			<div class="form-floating" id="actParamBlock${nextID}">
				<select class="form-select" id="actParamSelect${nextID}" name="actParamSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Eigenschaft</label>
			</div>
			<button class="btn btn-outline-secondary " type="button" id="btnActOperator${nextID}" name="btnActOperator${nextID}">&gt;</button>
			<div class="form-floating" id="actValBlock${nextID}">
				<input  type="number" class="form-control" id="actValue${nextID}" name="actValue${nextID}" placeholder="0" value="0"></input>
				<label>Sollwert</label>
			</div>
      <button class='btn btn-outline-danger' type='button' id='btnActDel${nextID}' data-delid="actorSettings${nextID}" onclick="delAutoEntry(event)"><i class="bi bi-trash3"></i></button>`;

    document.getElementById("actorsList").appendChild(div);
    /*"afterend",`<div class='input-group mb-3' id='actorSettings${nextID}'>
	  		<div class="form-floating">
        		<select class="form-select" id="actorSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Aktor</label>
			</div>
			<div class="form-floating" id="actParamBlock${nextID}">
				<select class="form-select" id="actParamSelect${nextID}" aria-label="Default select example">
				</select>
				<label>Eigenschaft</label>
			</div>
			<button class="btn btn-outline-secondary " type="button" id="btnActOperator${nextID}">&gt;</button>
			<div class="form-floating" id="actValBlock${nextID}">
				<input  type="number" class="form-control" id="actValue${nextID}" placeholder="0" value="0"></input>
				<label>Sollwert</label>
			</div>
      <button class='btn btn-outline-danger' type='button' id='btnActDel${nextID}' data-delid="actorSettings${nextID}" onclick="delAutoEntry(event)"><i class="bi bi-trash3"></i></button>
		</div>`);*/
    fillActorDD(nextID);
  }

  function arrangeSensorInputs(event){
    ID = Number(event.currentTarget.id.replace("sensorSelect",""));
    sensorID = document.getElementById("sensorSelect"+ID).value;
    
    fetch("./ajax/sensorDetails.php?sensorID="+sensorID, {
      method: 'GET',
      headers: {
        'X-Requested-From-Modal': 'a',
        'Requested-With-Ajax': 'ajax'
      }
    })
      .then(response => response.text())
      .then(html => {
        params = JSON.parse(html);
        document.getElementById("paramSelect"+ID).innerHTML = "";
        if(params.Parameters.length == 1){
          document.getElementById("paramBlock"+ID).hidden = true;
        }else{
          document.getElementById("paramBlock"+ID).hidden = false;
        }
        params.Parameters.forEach((param, index) => {
          var option = document.createElement("option");
          option.text = param.name;
          option.value = index;
          option.setAttribute("data-type",param.type);
          document.getElementById("paramSelect"+ID).appendChild(option);
          document.getElementById("btnOperator"+ID).setAttribute("data-tglstates",JSON.stringify(param.operators));
          document.getElementById("btnOperator"+ID).innerHTML = param.operators[0];
          document.getElementById("btnOperator"+ID).addEventListener("click", tglOperators);
          if(document.getElementById("btnLogic"+ID))
            document.getElementById("btnLogic"+ID).addEventListener("click", tglOperators);
          document.getElementById("threshold"+ID).setAttribute("type",param.type);
        });
        document.getElementById("paramSelect"+ID).dispatchEvent(new Event('change'));
      })
      .catch(error => {
        alert(error);
        document.getElementById("paramSelect"+ID).innerHTML = "";
      });
  }

  function arrangeActorInputs(event){
    ID = Number(event.currentTarget.id.replace("actorSelect",""));
    sensorID = document.getElementById("actorSelect"+ID).value;
    
    fetch("./ajax/actorDetails.php?actorID="+sensorID, {
      method: 'GET',
      headers: {
        'X-Requested-From-Modal': 'a',
        'Requested-With-Ajax': 'ajax'
      }
    })
      .then(response => response.text())
      .then(html => {
        params = JSON.parse(html);
        document.getElementById("actParamSelect"+ID).innerHTML = "";
        if(params.Parameters.length == 1){
          document.getElementById("actParamBlock"+ID).hidden = true;
        }else{
          document.getElementById("actParamBlock"+ID).hidden = false;
        }
        params.Parameters.forEach((param, index) => {
          var option = document.createElement("option");
          option.text = param.name;
          option.value = index;
          option.setAttribute("data-type",param.type);
          document.getElementById("actParamSelect"+ID).appendChild(option);
          if(param.operators === undefined){
            document.getElementById("btnActOperator"+ID).dataset.tglstates = "[\"=\"]";
            document.getElementById("btnActOperator"+ID).innerHTML = "=";
          }else{
            document.getElementById("btnActOperator"+ID).dataset.tglstates = JSON.stringify(param.operators);
            document.getElementById("btnActOperator"+ID).innerHTML = param.operators[0];
          }
          document.getElementById("btnActOperator"+ID).addEventListener("click", tglOperators);
          if(document.getElementById("btnActLogic"+ID)){
            document.getElementById("btnActLogic"+ID).addEventListener("click", tglOperators);
          }
          //if(document.getElementById("actParamSelect"+ID).value == param.id)
          //  document.getElementById("actValue"+ID).setAttribute("type",param.type);
        });
        document.getElementById("actParamSelect"+ID).dispatchEvent(new Event('change'));
      })
      .catch(error => {
        document.getElementById("actParamSelect"+ID).innerHTML = "";
      });
  }


  function tglOperators(event){
    btn = event.currentTarget;
    operators = JSON.parse(btn.dataset.tglstates);
    current = btn.innerHTML;
    btn.innerHTML = operators[(operators.indexOf(current)+1) % operators.length];
  }

  function loadAutomatic(params){
    if(params.search("action=new")>0){
      fillSensorDD("1");
      fillActorDD("1");
    }
  }

  function openAutoActionModal(params) {
    let contentURL = "./ajax/AutoAction.php"+params;
    if(params.search("action=new")>0)
      document.getElementById("modal-title").innerHTML = "Neue Automatik anlegen";
    else
      document.getElementById("modal-title").innerHTML = "Automatik Einstellungen";
    modalBodyElement = document.getElementById('modal-body');
    modalBodyElement.innerHTML = loadingHTML("Wird geladen...");
    document.getElementById("modalSaveBtn").addEventListener("click", submitFormAjax);
    document.getElementById("modalSaveBtn").contentURL = contentURL;
    modalEV.show();
    fetch(contentURL, {
      method: 'GET',
      headers: {
        'X-Requested-From-Modal': 'a',
        'Requested-With-Ajax': 'ajax'
      }
    })
      .then(response => response.text())
      .then(html => {
        modalBodyElement.innerHTML = html;
        loadAutomatic(params);
        document.getElementById("btnAddSensor").addEventListener("click", addSensor);
        document.getElementById("btnAddActor").addEventListener("click", addActor);
      })
      .catch(error => {
        modalBodyElement.innerHTML += error.message;
      });
  }