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

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

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

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

  <%- include('../../partials/modal/confirmation.ejs') %>
  <%- include('../../partials/modal/error.ejs') %>
  <%- include('../../partials/modal/addFirmware.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 py-3 overflow-auto">
                  <h5 class="card-title">
                    Firmwares
                    <button type="button" class="btn btn-primary mb-2 float-end" onclick="showAddFirmwareModal()"><i class="fa-solid fa-plus"></i></button>
                  </h5>
                  <table id="firmwares" class="display" style="width:100%">
                    <thead>
                        <tr>
                            <th></th>
                            <th>fw version</th>
                            <th>app version</th>
                            <th>release</th>
                            <th>variant</th>
                            <th>filename</th>
                        </tr>
                    </thead>
                  </table>
                </div>
              </div>
            </div>
          </div>
      </div>
  </div>

  <script>

    var t;
    var modelID = api.getModelID();

    function escapeHtml(str) {
      return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');
    }

    $(document).ready(function () {

      t = $('#firmwares').DataTable();

      api.getFWModelInfo(modelID,(err,res)=>{
        if(err) console.log(err);
        $("#title").text(res?.name)
      })

      api.getFirmwares(modelID,(err,res)=>{
        if(err) console.log("err:",err)
        else{
          res.forEach((item, i) => {
            addRow(item.id,item.version,item?.app_version,item.build_release,item?.variant_name || '',item.originalname,item.token);
            if(i == res.length-1){
              $(".fwReleaseOption").change((event)=>{
                let id = event.target.id;
                $( ".fwReleaseOption option:selected" ).each(function() {
                  let release = $( this ).text();
                  api.updateFwRelease(modelID,id,release,(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');
                    }
                  });
                });
              });
            }
          });
        }
      });

      // Load variants for the variant select dropdown
      api.getVariants(modelID,(err,res)=>{
        if(err) console.log("err:",err)
        else if(res && res.length > 0){
          res.forEach((item) => {
            let opt = document.createElement('option');
            opt.value = item.id;
            opt.textContent = item.name;
            document.getElementById('_variant_').appendChild(opt);
          });
        }
      });

    });

    function showAddFirmwareModal(){
      $('#modalAddFirmware').modal('show');
    }

    $("#submit_fw").click(()=>{
      let version = $("#_version_").val();
      let app_version = $("#_appversion_").val();
      let release = $("#_release_").val();
      let variant_id = $("#_variant_").val() || null;
      var input = document.getElementById("formFile");
      var file = input.files[0];
      
      // Validate inputs
      if(!version) {
        $('#error').text("FW version is required");
        $('#suggestion').text("Please enter a firmware version in format xx.yy.zz");
        $('#modalError').modal('show');
        return;
      }
      if(!release) {
        $('#error').text("Release is required");
        $('#suggestion').text("Please select a release type");
        $('#modalError').modal('show');
        return;
      }
      if(!file) {
        $('#error').text("File is required");
        $('#suggestion').text("Please select a firmware file");
        $('#modalError').modal('show');
        return;
      }
      
      // Check if filename contains fw version, app version and release
      let filename = file.name;
      if(!filename.includes(version)) {
        $('#error').text("Filename validation failed");
        $('#suggestion').text("Filename must contain the firmware version: " + version);
        $('#modalError').modal('show');
        return;
      }
      if(app_version && !filename.includes(app_version)) {
        $('#error').text("Filename validation failed");
        $('#suggestion').text("Filename must contain the app version: " + app_version);
        $('#modalError').modal('show');
        return;
      }
      if(!filename.includes(release)) {
        $('#error').text("Filename validation failed");
        $('#suggestion').text("Filename must contain the release: " + release);
        $('#modalError').modal('show');
        return;
      }
      
      api.addFirmware(modelID,file,version,app_version,release,variant_id,(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();
      });
    });

    function addRow(id,version,app_version,release,variant,filename,token){

      var hostname = window.location.protocol+"//"+window.location.hostname+":"+window.location.port;
      let fileUrl = hostname+"/api/firmware/"+filename+"/download?token="+token;
      t.row.add([`
        <button id="`+id+`" onclick="deleteFirmware('`+id+`');" type="button" class="delete btn btn-danger btn-sm">
          <i class="fa-sharp fa-solid fa-trash"></i>
        </button>`,
        version,
        app_version,
        `<select class="form-select fwReleaseOption" id="`+id+`">
          <option selected>`+release+`</option>
          <option value="dev">dev</option>
          <option value="staging">staging</option>
          <option value="prod">prod</option>
          <option value="critical">critical</option>
        </select>`,
        variant,
        `<a href="` + fileUrl + `" class="filename-link" title="` + escapeHtml(filename) + `">` + escapeHtml(filename) + `</a>`]).draw(true);

    }

    function deleteFirmware(id){

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

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