<!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') %>


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

  <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>Autorequests 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.ar_ref != null){%> disabled <%}%> id="sendARs" 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 arDeviceRef" id="_ar_ref_">
                <% if(device.device_id == device.ar_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>

  <!-- check link to more import options https://cdnjs.com/libraries/ace -->
  <!-- dark theme -->
  <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.14.0/ace.js" integrity="sha512-WYlXqL7GPpZL2ImDErTX0RMKy5hR17vGW5yY04p9Z+YhYFJcUUFRT31N29euNB4sLNNf/s0XQXZfzg3uKSoOdA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>-->
  <script src="./assets/js/ace.js"></script>
  <script>
      var editor = ace.edit("editor");
      var project_name = "";
      var uid = "";

      editor.setValue(`
//Example - remove this line
{
  "autorequests":
  {
    "rs485": [
      {
        "ref": "Itemp",
        "modbus": [1,3,834,2],
        "type": "UINT32BE",
        "period":60
      },
      {
        "ref": "Ipress",
        "modbus": [1,3,836,2],
        "type": "UINT16BE",
        "period":60
      },
      {
        "ref": "Ivb",
        "modbus": [1,3,806,4],
        "type": "INT16BE",
        "period":60
      },
      {
        "ref": "Ivc",
        "modbus": [1,3,810,4],
        "type": "FLOATBE",
        "period":60
      }]
  }
}
      `)

      deviceID = api.getDeviceID();

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


        documentation.innerHTML = marked.parse(`
##### Autorequest

    This module configures autorequests on respective device.

    Each autorequest is associated to a sensor that must be configured.
    A sensor is configured with a ref and a period field and must be contained on a category

    For now only sensors of rs485 category are available

    Send '{}' to clean autorequests on device
##### RS485

      - ref (mandatory)
      - period (mandatory)
      - type (mandatory)
      - modbus (mandatory)

    Modbus is an array with the modbus packet [unit_id,fc,address,length].
    Only fc 3 and 4 are available for now for autorequests.

##### Type

    Type identifies the type of the value read. It can be:

      - UINT8
      - INT16BE
      - INT16LE
      - UINT16BE
      - UINT16LE
      - INT32BE
      - INT32LE
      - UINT32BE
      - UINT32LE
      - FLOATBE
      - FLOATLE
      - HEX*
      - CHAR*

      `);

        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 ar = null;
        try{
          ar = JSON.parse(JSON.stringify(device.ar));
        }catch(e){console.log(e)}

        if(ar != null)
          editor.setValue(JSON.stringify(ar,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/ar/#");
      }

      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 sendARs(payload){
        message = new Paho.MQTT.Message(payload);
        message.destinationName = project_name+"/"+uid+"/fw/ar/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);
        });
      }

      $("#sendARs").click(()=>{
        // call JSON validator
        let data = editor.getValue()
        let text = data.replace(/ /g,'');
        text = text.replace(/\n/g,'');

        try{
          //JSON.parse(text)
          //sendARs(JSON.stringify(text));
          sendARs(text);
        }catch(e){
          $('#error').text("Not JSON");
          $('#suggestion').text("check if file has comments");
          $('#modalError').modal('show');
        }
      })

      $(".arDeviceRef").change((event)=>{
        $( ".arDeviceRef option:selected" ).each(function() {
          let dev_ref = $( this ).val();
          if(dev_ref == "null")
            dev_ref = null;
          api.updateDeviceProjectField(deviceID,"ar_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>
