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

  <style>
    td.center {
      text-align:left;
    }

    td {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 150px;  /* Or whatever width you want */
    }

  </style>

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

</head>
<body>

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

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

  <link href="./assets/css/jquery.dataTables.min.css" rel="stylesheet"></script>
  <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/model/sidebar.ejs') %>
      <div class="col py-3">
        <div class="content-header">
          <h3><%= model.name %></h3>
        </div>
      <div class="row">
        <!--<div class="col-sm-12 mb-3 mb-sm-0">-->
        <div class="card overflow-auto" style="width:100%">
          <div class="card-body">
            <div class="row g-3 mb-3">
              <div class="col-md-4">
                <label for="variantFilter" class="form-label">Variant</label>
                <select id="variantFilter" class="form-select form-select-sm">
                  <option value="">All variants</option>
                </select>
              </div>
            </div>
            <table id="devices" class="display">
              <caption><b>Devices</b></caption>
              <thead>
                <tr>
                  <th></th>
                  <th>uid</th>
                  <th>project</th>
                  <th>variant</th>
                  <th>status</th>
                  <th>version</th>
                  <th>versionApp</th>
                  <th>created</th>
                  <th>updated</th>
                </tr>
              </thead>
            </table>
          </div>
        </div>
        <!--</div>-->
      </div>
    </div>
  </div>

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

  <script>
    var t;
    var id;
    let devices = <%- JSON.stringify(devices) %>;

    $(document).ready(function () {
      t = $('#devices').DataTable();
      bindVariantFilter();
      syncVariantFilter(devices || []);

      if(devices?.length > 0){
        devices.forEach((item, i) => {
        addRow(item.id,item.uid,item.project,item.model,item.model_id,moment(item.createdAt).format('YY/MM/DD LT'),
          item.status,item?.version,item?.app_version,moment(item.updatedAt).format('YY/MM/DD LT'),item.variant);
        });
      }
    });

    function escapeDataTableValue(value){
      return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }

    function applyExactColumnFilter(columnIndex, value){
      t.column(columnIndex).search(
        value ? '^' + escapeDataTableValue(value) + '$' : '',
        true,
        false
      ).draw();
    }

    function syncVariantFilter(rows){
      const variantFilter = document.getElementById('variantFilter');
      const currentValue = variantFilter.value;
      variantFilter.innerHTML = '<option value="">All variants</option>';

      [...new Set((rows || []).map(item => item.variant).filter(value => value != null && value !== ''))]
        .sort((a, b) => String(a).localeCompare(String(b)))
        .forEach(value => {
          const option = document.createElement('option');
          option.value = value;
          option.textContent = value;
          variantFilter.appendChild(option);
        });

      variantFilter.value = currentValue;
    }

    function bindVariantFilter(){
      document.getElementById('variantFilter').addEventListener('change', function() {
        applyExactColumnFilter(3, this.value);
      });
    }

    function addRow(id,uid,project,model,model_id,created,status,version,versionApp,updated,variant){

      if(uid.startsWith("uid:")){
        uid = uid.substring(4);
      }
      t.row.add([`
        <div class="btn-group">
          <button onclick="deleteDevice('`+id+`');" type="button" class="delete btn btn-secondary btn-sm">
            <i class="fa-solid fa-user-xmark"></i>
          </button>
        </div>`,
        `<a href="../../../device/`+id+`">`+uid+`</a>`,
        project,variant||'',status,version,versionApp,created,updated]).draw(true);
    }

    function deleteDevice(device_id){
      id = device_id;
      $('#modalConfirmation').modal('show');
    }

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

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