<!DOCTYPE html>
<html lang="en">
<head>

  <%- include('../../partials/head.ejs') %>

  <style type="text/css" media="screen">
      #editor {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
      }

      .card {
        height: 500px;
      }
  </style>
</head>
<body>

  <%- include('../../partials/scripts.ejs') %>
  <%- include('../../partials/device/navbar.ejs') %>

  <%- include('../../partials/modal/confirmation.ejs') %>
  <%- include('../../partials/modal/error.ejs') %>
  <%- include('../../partials/modal/loading.ejs') %>
  <%- include('../../partials/modal/timeout.ejs') %>

  <div class="container-fluid">
      <div class="row flex-nowrap">
          <%- include('../../partials/device/sidebar.ejs') %>
          <div class="col py-3">
            <div class="row">
              <div class="col-sm-8 mb-3 mb-sm-0">
                <div class="content-header">
                  <h5>Alarms editor
                    <button id="mqtt_status" type="button" class="btn btn-secondary" disabled></button>
                  </h5>
                </div>
                <div class="card">
                  <!--<h5 class="card-title">Special title treatment</h5>-->
                    <div id="editor">
                    </div>
                </div>
                <button <% if(device.alarms_ref != null){%> disabled <%}%> id="sendAlarm" type="button" class="btn btn-primary">update</button>
                  <div class="btn-group" style="float:right">
                <label class="input-group-text" for="inputGroupSelect21">use device config:</label>
                <select class="form-select alarmDeviceRef" id="_alarm_ref_">
                  <% if(device.device_id == device.alarms_ref){ %>
                    <option selected value="null">own</option>
                  <%} else {%>
                    <option value="null">own</option>
                  <% } %>
                </select>
              </div>
              </div>
              <div class="col-sm-4 mb-2 mb-sm-0">
                <div class="content-header">
                  <h5><%= device.name != null ? device.name : device.uid %>
                    <button id="status" type="button" class="btn btn-secondary" disabled></button>
                  </h5>
                </div>
                <div class="card">
                  <div class="card-header">
                    <p>Documentation</p>
                  </div>
                  <div class="card-body" style="overflow-y:scroll">
                    <div id="documentation">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
      </div>
  </div>

  <script src="lib/marked.js"></script>

  <script src="./assets/js/ace.js"></script>
  <script src="./assets/js/mqttws31.min.js" type="text/javascript"></script>

  <script>
    var editor = ace.edit("editor");
    editor.setValue(`
//Example - remove this line
{
  "alarms": [
    {
      "ref": "Itemp",
      "min_value":15,
      "max_value":30,
      "period":15
    },
    {
      "ref": "Ipress",
      "min_value":1.1,
      "period":15
    },
    {
      "ref": "Ivb",
      "diff":1,
      "max_value":10,
      "period":15
    },
    {
      "ref": "Ivc",
      "period":15
    }
  ]
}
      `)

    deviceID = api.getDeviceID();
    var project_name = "";
    var uid = "";

    $(document).ready(()=>{

      documentation.innerHTML = marked.parse(`

  This module configures alarms on respective device.

  Send '{}' to clean arlarms on device

  Minimum and maximum values for safe zone can be set, using min_value and max_value fields.

  Is even possible to use diff field to calculate the difference between current and last read value.

  Period in which the values are checked are set using period field.

  The alarm execution forces a sensor read of the sensor configured on Autorequests tab. Sensor is identified by ref field

  Each alarm has the following fields that can be configured:

    - ref (mandatory)
    - period (mandatory)
    - min_value
    - max_value
    - diff

  Note: check if a field for inside or outside zone is available
      `);

      let device = <%- JSON.stringify(device) %>;
      let mqtt = <%- JSON.stringify(mqtt) %>;
      project_name = <%- JSON.stringify(project_name) %>;
      uid = device.uid;

      client = new Paho.MQTT.Client(Settings.mqtt.host, Settings.mqtt.port, mqtt.nick);

      // set callback handlers
      client.onConnectionLost = onConnectionLost;
      client.onMessageArrived = onMessageArrived;

      client.connect({
        userName:mqtt.type,
        password:mqtt.password,
        useSSL:Settings.mqtt.ssl,
        timeout:3,
        onSuccess:onConnect
      });

      let alarms = null;
      try{
        alarms = JSON.parse(JSON.stringify(device.alarms));
      }catch(e){console.log(e)}

      if(alarms != null)
        editor.setValue(JSON.stringify(alarms,null,2));

    });

    // called when the client connects
    function onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      let button = document.querySelector('#mqtt_status');
      button.classList.toggle("btn-secondary",false);
      button.classList.toggle("btn-success",true);
      client.subscribe(project_name+"/"+uid+"/status");
      client.subscribe(project_name+"/"+uid+"/fw/alarms/#");
    }

    function onConnectionLost(responseObject) {
      button.classList.toggle("btn-secondary",false);
      button.classList.toggle("btn-danger",true);
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:"+responseObject.errorMessage);
      }
    }

    function onMessageArrived(message) {

      let topic = message.destinationName;
      let payload = message.payloadString;
      if(topic.includes("status")){
        let button = document.querySelector('#status');
        button.classList.toggle("btn-secondary",false);
        if(payload == "online")
          button.classList.toggle("btn-success",true);
        else
          button.classList.toggle("btn-danger",true);
      }

      if(topic.endsWith("set")){
        if(payload == "" || payload == null || payload === 'undefined'){
          $(document).trigger("closeModalLoading"); // set confirmation
        }
      }
    }

    function sendAlarms(payload){
      message = new Paho.MQTT.Message(payload);
      message.destinationName = project_name+"/"+uid+"/fw/alarms/set";

      var loading = $('#modalLoading');
      loading.modal('show');
      setTimeout(()=>{
        client.send(message);
      },500)

      var timeoutId = setTimeout(()=>{
        loading.modal('hide'); // set confirmation
        $('#modalTimeout').modal('show');
      },15000);

      $(document).on("closeModalLoading", function() {
        loading.modal('hide'); // set confirmation
        clearTimeout(timeoutId);
      });
    }

    $("#sendAlarm").click(()=>{
      let data = editor.getValue()
      let text = data.replace(/ /g,'');
      text = text.replace(/\n/g,'');
      try{
        //JSON.parse(text)
        //sendAlarms(JSON.stringify(text));
        sendAlarms(text);
      }catch(e){
        $('#error').text("Not JSON");
        $('#suggestion').text("check if file has comments");
        $('#modalError').modal('show');
      }
    })

    $(".alarmDeviceRef").change((event)=>{
        $( ".alarmDeviceRef option:selected" ).each(function() {
          let dev_ref = $( this ).val();
          if(dev_ref == "null")
            dev_ref = null;
          api.updateDeviceProjectField(deviceID,"alarms_ref",dev_ref,(err,res)=>{
            if(err){
              $('#error').text("Your request cannot be executed");
              if(err.hasOwnProperty("sqlMessage"))
                $('#suggestion').text(err.sqlMessage);
              else
                $('#suggestion').text(err);
              $('#modalError').modal('show');
            }else{
              location.reload();
            }
          });

        });
      });

  </script>
</body>
</html>
