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

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

  <style>
    td {
      max-width: 200px;
    }
  </style>
</head>
<body>

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

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

  <link href="./assets/css/jquery.dataTables.min.css" rel="stylesheet"></link>
  <script src="./assets/js/jquery.dataTables.min.js"></script>
  <script src="./assets/js/fontawesome.js"></script>

  <div class="container-fluid">
      <div class="row flex-nowrap">
          <%- include('../partials/sidebar.ejs') %>
          <div class="col py-3">
            <div class="row">
              <div class="col-sm-7 mb-3 mb-sm-0">
                <div class="content-header">
                  <h5>MQTT Clients</h5>
                </div>
                <div class="card overflow-auto">
                  <!--<h5 class="card-title">Special title treatment</h5>-->
                  <table id="clients" class="display" style="width:100%">
                    <thead>
                        <tr>
                            <th></th>
                            <th>client</th>
                            <th>password</th>
                            <th>user type</th>
                            <th>registered</th>
                        </tr>
                    </thead>
                  </table>
                </div>
              </div>
              <div class="col-sm-5 mb-2 mb-sm-0">
                <div class="card">
                  <div class="card-header">
                    <p>Add new client</p>
                  </div>
                  <div class="card-body">
                    <div class="input-group mb-3">
                      <span class="input-group-text" >client</span>
                      <input type="text" id="_clientID_" class="form-control" placeholder="mqtt client/platform client" aria-label="Username" aria-describedby="basic-addon1">
                    </div>
                    <div class="input-group mb-3">
                      <span class="input-group-text" >password</span>
                      <input type="text" id="_passwordID_" class="form-control" placeholder="platform password" aria-label="Password" aria-describedby="basic-addon1">
                    </div>
                    <div class="input-group mb-3">
                      <label class="input-group-text" for="inputGroupSelect01">user</label>
                      <select class="form-select" id="_userID_">
                        <!--<option default>client</option>-->
                      </select>
                    </div>
                    <button id="submit" type="button" class="btn btn-primary btn-sm">submit</button>
                    <br>
                    <br>
                    <div id="privelleges">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
      </div>
  </div>

  <script src="./assets/js/ace.js"></script>
  <script type="module" src="./app.mjs"></script>

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

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

  <script>
    var t;
    var id;

    privelleges.innerHTML = marked.parse(
    `#### Clients Privelleges:

    Only clients listed on this section are available to access mqtt broker.
    Create a client and associate it to a user.
    Clients permissions will be given by associated user type.
    Those permissions are then used by mqtt broker to manage privelleges on subscribe and publish topics.

    However, it is possible to give permission to a client to manage one or more devices, clicking on it's id in this table

    These clients accounts are also used to login on this platform.
    So the defined password on new client creation will be used to login on this platform.
    `);

    $(document).ready(function () {

      t = $('#clients').DataTable();
      api.getClients((err,res)=>{
        if(err) console.log("err:",err)
        else{
          res.forEach((item, i) => {
            addRow(item.id,item.nick,item.token,item.api_token,item.type,moment(item.createdAt).format('YY/MM/DD LT'));
          });
        }
      });

      api.getUsers((err,res)=>{
        if(err) console.log("err:",err)
        else{
          res.forEach((item, i) => {
            addOption("#_userID_",item.id,item.type)
          });
        }
      })
    });

    function addOption(element, id, user_id, selected){

      if(selected) $(element).append(`<option selected value="${id}">${user_id}</option>`);
      else $(element).append(`<option value="${id}">${user_id}</option>`);
    }

    function addRow(clientId,nick,password,api_token,user,registered){
      if(nick.indexOf("uid:") > -1)
          return;
      if(password == null)
        password = "";
      t.row.add([`
        <div class="btn-group">
          <button onclick="deleteClient('`+clientId+`');" type="button" class="delete btn btn-secondary btn-sm">
            <i class="fa-solid fa-user-xmark"></i>
          </button>
          <button onclick="editClient('`+clientId+`,`+password+`,`+user+`');" type="button" class="edit btn btn-primary btn-sm">
            <i class="fa-solid fa-user-pen"></i>
          </button>
        </div>`,
        `<a href="./client/`+clientId+`">`+nick+`</a>`,
        `<div class="btn-group">
          <label for="inputPassword2" class="sr-only">Password</label>
          <input type="password" disabled class="form-control" id='`+clientId+`' name="password" value=`+password+`>
          <button type="button" class="btn mb-2" onclick="togglePasswordVisibility('`+clientId+`')">
            <i class="bi bi-eye-fill"></i>
          </button>
        </div>`,
        user,
        registered]).draw(true);
    }

    function togglePasswordVisibility(client_id) {
      var passwordField = document.getElementById(client_id);
      if (passwordField.type === "password") passwordField.type = "text";
      else passwordField.type = "password";
    }

    function deleteClient(client_id){
      id = client_id;
      $('#modalConfirmation').modal('show');
    }

    function editClient(args){
      let arr = args.split(",");
      let client_id = arr[0];
      let pwd = arr[1];
      let user_type = arr[2];
      id = client_id;

      const myInput = document.getElementById('_modalPasswordID_');
      // Change the value of the input element
      console.log("pwd:",pwd)
      if(typeof pwd !== "undefined"){
        if(pwd == "null") myInput.value = "";
        else myInput.value = pwd;
      }

      const mySelect = document.getElementById('_modalUserType_');
      while (mySelect.options.length > 0) {
        mySelect.remove(0);
      }
      api.getUsers((err,res)=>{
        if(err) console.log("err:",err)
        else{
          res.forEach((item, i) => {
            if(user_type == item.type)
              addOption("#_modalUserType_",item.id,item.type,true)
            else
              addOption("#_modalUserType_",item.id,item.type)
          });
        }
      })

      $('#modalEditClient').modal('show');
    }

    $("#modalProceed").click(()=>{
      api.deleteClient(id,(err,res)=>{
        if(err){
          $('#error').text("Your request cannot be executed");
          $('#suggestion').text(err);
          $('#modalError').modal('show');
        }else location.reload();
      });
    })

    $("#modalChangeClientSettings").click(()=>{
      let pwd = $("#_modalPasswordID_").val();
      let user_type = $("#_modalUserType_").val();

      api.updateClient(id,pwd,user_type,(err,res)=>{
        if(err){
          $('#error').text("Your request cannot be executed");
          $('#suggestion').text(err);
          $('#modalError').modal('show');
        }else location.reload();
      });

    });

    $("#submit").click(()=>{
      let client = $("#_clientID_").val();
      let user = $("#_userID_").val();
      let password = $("#_passwordID_").val();
      api.addClient(client,user,password,(err,res)=>{
        if(err) console.log(err);
        else location.reload();
      });
    });

  </script>

</body>
</html>
