<!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/scripts.ejs') %>
  <%- include('../partials/navbar.ejs') %>

  <%- include('../partials/modal/confirmation.ejs') %>
  <%- include('../partials/modal/error.ejs') %>
  <%- include('../partials/modal/success.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" crossorigin="anonymous"></script>

  <div class="container-fluid">
      <div class="row flex-nowrap">
          <%- include('../partials/sidebar.ejs') %>
          <div class="col py-3">
            <div class="content-header">
              <div class="d-flex align-items-center justify-content-between">
                <h3>Models</h3>
                <% if(user.level == 5){ %>
                <button id="openModelBtn" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#modelModal">
                  + 
                </button>
                <%}%>
              </div>
            </div>
            <div class="row">
              <div class="col-sm-12 mb-3 mb-sm-0">
                <div class="card py-3 overflow-auto" style="width:100%">
                  <table id="models" class="display">
                    <thead>
                        <tr>
                            <th></th>
                            <th>model</th>
                            <th>description</th>
                            <th>variants</th>
                        </tr>
                    </thead>
                  </table>
                </div>
              </div>
              <!--
              <div class="col-sm-4 mb-3 mb-sm-0">
                <div class="card py-3">
                  <div class="card-header">
                    <h5 class="card-title">Add new model</h5>
                  </div>
                  <div class="card-body">
                    <div class="mb-3">
                      <div class="input-group py-2">
                        <label class="input-group-text" for="inputGroupSelect11">name</label>
                        <input type="text" id="_name_" class="form-control" placeholder="set your model name">
                      </div>
                      <div class="py-2">
                        <label class="input-group-text" for="inputGroupSelect12">description</label>
                        <textarea id="_description_" class="form-control" aria-label="With textarea"></textarea>
                      </div>
                      <div class="py-2">
                        <button id="submit_model" type="button" class="btn btn-primary btn-sm">submit</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              -->
            </div>
          </div>
      </div>
  </div>

<!-- Modal for Model Creation -->
<div class="modal fade" id="modelModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <form class="modal-content" id="modelForm" novalidate>
      <div class="modal-header">
        <h5 class="modal-title">Add Model</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <div class="modal-body">
        <!-- Project -->
        <div class="mb-3">
          <label for="projectSelect" class="form-label">Project</label>
          <select id="projectSelect" class="form-select" required>
            <!-- populated by JS -->
          </select>
          <div class="invalid-feedback">Please select a project.</div>
        </div>

        <!-- Model Name -->
        <div class="mb-3">
          <label for="modelName" class="form-label">Model Name</label>
          <input id="modelName" class="form-control" type="text" placeholder="e.g. SLIM_GW_WIFI" required />
          <div class="invalid-feedback">Please enter a model name.</div>
        </div>

        <!-- Description -->
        <div class="mb-3">
          <label for="modelDescription" class="form-label">Description</label>
          <textarea id="modelDescription" class="form-control" rows="3" placeholder="Model description..."></textarea>
          <div class="invalid-feedback">You can add a description.</div>
        </div>
        
      </div><!-- /.modal-body -->

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
      </div>
    </form>
  </div>
</div>

  <script>

    var t;
    var id;
    let models = <%- JSON.stringify(models) %>;
    let user = <%- JSON.stringify(user) %>;

    $(document).ready(function () {

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

      models.sort((a, b) => (a.name.toLowerCase() > b.name.toLowerCase()) ? 1 : ((b.name.toLowerCase() > a.name.toLowerCase()) ? -1 : 0));

      models.forEach((item, i) => {
        addRow(item.id,item.name,item.description);
      });

      // Load projects for the project selection dropdown
      api.getProjects((err, res) => {
        if (err) {
          console.error("Error fetching projects:", err);
          return;
        }

        const projectSelect = document.getElementById('projectSelect');
        
        // Clear any existing options
        projectSelect.innerHTML = '';

        // Create a placeholder option
        const placeholderOption = document.createElement('option');
        placeholderOption.value = '';
        placeholderOption.textContent = 'Select a project';
        projectSelect.appendChild(placeholderOption);

        // Populate the select element with projects
        res.forEach(project => {
          const option = document.createElement('option');
          option.value = project.id;
          option.textContent = project.name;
          projectSelect.appendChild(option);
        });
      });

      /*
      api.getFWModels((err,res)=>{
        if(err) console.log("err:",err)
        else{
          res.forEach((item, i) => {
            addRow(item.id,item.name,item.description);
          });
        }
      });
      */
    });

    function addRow(id,model,description){
      const buttonHtml = `
        <button 
          id="${id}" 
          onclick="deleteModel('${id}');" 
          type="button" 
          class="delete btn btn-secondary btn-sm"
          ${user.level !== 5 ? 'disabled' : ''}
        >
          <i class="bi bi-folder-x"></i>
        </button>`;

      t.row.add([
        buttonHtml,
        `<a href="./model/`+id+`/devices">`+model+`</a>`,
        description,
        `<a href="./model/`+id+`/variants">view</a>`]).draw(true);
    }

    // Handle new model form submission
    document.getElementById('modelForm').addEventListener('submit', function(event) {
      event.preventDefault(); // Prevent form from submitting the default way

      // Get form values
      const projectSelect = document.getElementById('projectSelect');
      const modelName = document.getElementById('modelName').value.trim();
      const modelDescription = document.getElementById('modelDescription').value.trim();

      // Validate fields before calling API
      if (projectSelect.value === '' || modelName === '') {
        $('#error').text("Some required fields are empty");
        $('#suggestion').text("Please select a project and enter a model name");
        $('#modalError').modal('show');
        return;
      }

      // Call API to add model
      api.addModel(modelName, parseInt(projectSelect.value), modelDescription, (err, res) => {
        if(err){
          $('#error').text("Error adding model");
          if(err.hasOwnProperty("sqlMessage"))
            $('#suggestion').text(err.sqlMessage);
          else
            $('#suggestion').text(err);
          $('#modalError').modal('show');
        }else{
          // Show success message
          $("#successHeader").text("Model successfully added");
          $('#successMsg').text("Model '" + modelName + "' has been created successfully");
          $('#modalSuccess').modal('show');
          
          // Reload page to show the new model
          setTimeout(() => {
            location.reload();
          }, 2000);
          
        }

        // Close modal
        var modalInstance = bootstrap.Modal.getInstance(document.getElementById('modelModal'));
        if (modalInstance) {
          modalInstance.hide();
        }

        // Reset the form
        document.getElementById('modelForm').reset();
      });
    });

    function deleteModel(model_id){
      id = model_id
      $('#modalConfirmation').modal('show');
    };

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

    // SLIM_GW_WIFI
    // firmware to run on TD SLIM GW device. It supports rs485 and 4 digital inputs. Only wifi is enabled in this version

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