{% extends "main.html" %}

{% block header %}
  <div class="row mb-2">
    <div class="col-sm-6">
      <h1>{{ page_title | safe }}</h1>
    </div>
    <div class="col-sm-6">
      <a class="btn btn-outline-primary float-sm-right mr-4" href="#" data-toggle="modal" data-target="#addModal" title="Add Project" aria-hidden="true">
        <i class="fas fa-plus fa-sm fa-fw"></i> Project
      </a>
    </div>
  </div>
{% endblock header %}

{% block content %}
  <div class="col-12">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">Projects</h3>
        <div class="card-tools">
          <button type="button" class="btn btn-tool" onclick="reloadPageContent()" title="Refresh">
          <i class="fas fa-sync"></i>
          </button>
        </div>
      </div>
      <div class="card-body">
        <table class="table table-hover" id="myDataTable" width="100%" cellspacing="0">
        </table>
      </div>
    </div>
  </div>
{% endblock content %}

{% block modal %}
  {% include 'modals/projects.html' %}
{% endblock modal %}

{% block script %}
  <script>
    var reloadTime = 10000;
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const serverId = urlParams.get('id');
    const project = urlParams.get('project');
    var editedProject = ''
    applySidebarStyles();
    applySidebarLinks();
    populateSidebarLinks();
    populateNavbarLinks();

    function reloadPageContent() {
      //Clear the automatic page reload
      clearTimeout(pageReloadTimeout);

      //Reload the datatables content
      $('#myDataTable').DataTable().ajax.reload(null, false);

      //Set the automatic page reload
      pageReloadTimeout = setTimeout(() => { reloadPageContent(); }, reloadTime);
    }

    function loadPageContent(){

      //Display the current project
      $("#selectedProject").text(project);

      //Populate the Server dropdown
      $.getJSON("../api/servers/list_servers?id="+serverId+"&project="+project, function (data) {
        data = data.data
        for (var index = 0; index < data.length; index++) {
          if (data[index].name == '')
            optionText = data[index].addr
          else
            optionText = data[index].name
          if (data[index].id == serverId)
            $('#serverListNav').append('<option value="' + data[index].id + '" selected="selected">' + optionText + '</option>');
          else
            $('#serverListNav').append('<option value="' + data[index].id + '">' + optionText + '</option>');
        }
      })

      //Populate the Project dropdown
      $.getJSON("../api/projects/list_projects?id="+serverId+"&project="+project, function (data) {
        data = data.metadata
        for (var index = 0; index < data.length; index++) {
          optionText = data[index].replace('/1.0/projects/','');
          if (optionText == project)
            $('#projectListNav').append('<option value="' + optionText + '" selected="selected">' + optionText + '</option>');
          else
            $('#projectListNav').append('<option value="' + optionText + '">' + optionText + '</option>');
        }
      })

      // Configure Datatable
      $('#myDataTable').DataTable({
        ajax: {
          url: "../api/projects/list_projects?id="+serverId+"&project="+project+"&recursion=1",
          dataType: "json",
          dataSrc: "metadata",
          contentType: "application/json"
        },
        columns: [
          { title: "Name", data: function (row, type, set) {
              if (row.hasOwnProperty('name')) {
                if (row.name)
                  return row.name
              }
              return '-'
            },
          },
          { title: "Description", data: function (row, type, set) {
              if (row.hasOwnProperty('description')) {
                if (row.description)
                  return row.description
              }
              return '-'
            },
          },
          { title: "Featured Items", data: function (row, type, set) {
              arr = []
              for (item in row.config) {
                if (item.startsWith('features.')) {
                  if (row.config[item] == 'true')
                    arr.push(item.replace('features.',''))
                }
              }
              if (arr.length > 0)
                return arr.join(", ")
              return '-'
            },
          },
          { title: "Actions", data: function (row, type, set) {
              links = ''
              if (row.hasOwnProperty('name')) {
                links = '<a href="#" onclick=editProject(\''+row.name+'\')><i class="fas fa-edit fa-lg" style="color:#ddd" title="Edit" aria-hidden="true"></i></a>' +
                '&nbsp' + '&nbsp' +
                '<a href="#" onclick=renameProject(\''+row.name+'\')><i class="fas fa-tag fa-lg" style="color:#ddd" title="Rename" aria-hidden="true"></i></a>' +
                '&nbsp' + '&nbsp' +
                '<a href="#" onclick=confirmDeleteProject(\''+row.name+'\')><i class="fas fa-trash-alt fa-lg" style="color:#ddd" title="Delete" aria-hidden="true"></i></a>'
              }
              return links
            },
          },
        ],
        order: [],
      });

      //Set reload page content
      pageReloadTimeout = setTimeout(() => { reloadPageContent(); }, reloadTime);

    }

    function changeRestrictedOptionsDisplay(){
      var projectRestrictedInput = $("#addModalRestrictedInput").val();

      if (projectRestrictedInput == "true"){
        $("#projectRestrictedBackupsRow").show();
        $("#projectRestrictedClusterTargetRow").show();
        $("#projectRestrictedContainersLowlevelRow").show();
        $("#projectRestrictedContainersNestingRow").show();
        $("#projectRestrictedContainersPrivilegeRow").show();
        $("#projectRestrictedDevicesDiskRow").show();
        $("#projectRestrictedDevicesGpuRow").show();
        $("#projectRestrictedDevicesInfinibandRow").show();
        $("#projectRestrictedDevicesNicRow").show();
        $("#projectRestrictedDevicesPciRow").show();
        $("#projectRestrictedDevicesProxyRow").show();
        $("#projectRestrictedDevicesUnixBlockRow").show();
        $("#projectRestrictedDevicesUnixCharRow").show();
        $("#projectRestrictedDevicesUnixHotplugRow").show();
        $("#projectRestrictedDevicesUsbRow").show();
        $("#projectRestrictedNetworksSubnetsRow").show();
        $("#projectRestrictedNetworksUplinksRow").show();
        $("#projectRestrictedSnapshotsRow").show();
        $("#projectRestrictedVirtualMachinesLowlevelRow").show();
      }
      else {
        $("#projectRestrictedBackupsRow").hide();
        $("#projectRestrictedClusterTargetRow").hide();
        $("#projectRestrictedContainersLowlevelRow").hide();
        $("#projectRestrictedContainersNestingRow").hide();
        $("#projectRestrictedContainersPrivilegeRow").hide();
        $("#projectRestrictedDevicesDiskRow").hide();
        $("#projectRestrictedDevicesGpuRow").hide();
        $("#projectRestrictedDevicesInfinibandRow").hide();
        $("#projectRestrictedDevicesNicRow").hide();
        $("#projectRestrictedDevicesPciRow").hide();
        $("#projectRestrictedDevicesProxyRow").hide();
        $("#projectRestrictedDevicesUnixBlockRow").hide();
        $("#projectRestrictedDevicesUnixCharRow").hide();
        $("#projectRestrictedDevicesUnixHotplugRow").hide();
        $("#projectRestrictedDevicesUsbRow").hide();
        $("#projectRestrictedNetworksSubnetsRow").hide();
        $("#projectRestrictedNetworksUplinksRow").hide();
        $("#projectRestrictedSnapshotsRow").hide();
        $("#projectRestrictedVirtualMachinesLowlevelRow").hide();
      }
    }

    function confirmDeleteProject(projectToDelete){
      console.log("Info: confirming deletion of project " + projectToDelete);
      if (confirm("Are you sure you want to delete project " + projectToDelete + "?") == true) {
        deleteProject(projectToDelete);
      }
    }

    function addItem(){
      console.log("Info: adding new project");
      data = $('#addForm').serialize();
      $.post("../api/projects/add_project?id="+serverId+"&project="+project, data, function (data) {
        console.log(data)
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    }

    function createProjectUsingJSON(){
      var projectCreateJSON = $("#jsonCreateInput").val();
      console.log("Info: adding new project");
      $.post("../api/projects/add_project?id="+serverId+"&project="+project, { json: projectCreateJSON },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    }

    function deleteProject(projectToDelete){
      console.log("Info: deleting project " + projectToDelete);
      $.get("../api/projects/delete_project?id=" + serverId + "&project=" + project + "&name=" + encodeURI(projectToDelete), function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    }

    function editProject(name){
      editedProject = name
      console.log("Info: loading project " + name);
      $.get("../api/projects/load_project?id=" + serverId + "&project=" + project + "&name=" + encodeURI(name), function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        $("#projectNameEditInput").text("Name: " + name);
        $("#jsonInput").val(JSON.stringify(data.metadata, null, 2));
        $("#editModal").modal('show');
      });
    }

    function renameProject(name){
      console.log("Loading rename modal for project " + name)
      $("#renameProjectModalLabel").text("Rename project: " + name);
      $("#projectToRename").val(name);
      $("#renameModal").modal('show');
    }

    function updateProject(){
      name = editedProject
      var updatedJSON = $("#jsonInput").val();
      console.log("Info: updating project");
      $.post("../api/projects/update_project?id=" + serverId + "&project=" + project + "&name=" + encodeURI(name), { json: updatedJSON },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    }

    function updateProjectName(){
      var projectNewName = $("#newProjectName").val();
      var projectToRename = $("#projectToRename").val();
      console.log("Info: renaming project " + projectToRename);
      $.post("../api/projects/update_project?id=" + serverId + "&project=" + project + "&name=" + encodeURI(projectToRename), { 'name': projectNewName },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    } 

    $(document).ready(function(){

      //If id or project variables are missing redirect to servers page
      if (!serverId || !project) {
        window.location.href = 'servers';
      }
      else {
        loadPageContent()
        operationStatusCheck()
      }
      
    });

  </script>
{% endblock script %}