{% 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">
      <button class="btn btn-outline-primary float-sm-right mr-4" data-bs-toggle="modal" data-bs-target="#addModal" title="Add Network Zone" aria-hidden="true">
        <i class="fas fa-plus fa-sm fa-fw"></i> Network Zone
      </button>
    </div>
  </div>
{% endblock header %}

{% block content %}
  <div class="col-12">
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">Network Zones</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/network-zones.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 editedNetworkZone = ''
    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);

      //Loaded from main.html template
      populateServerSelectDropdown()
      populateProjectSelectDropdown()
      
      // Configure Datatable
      $('#myDataTable').DataTable({
        ajax: {
          url: "../api/network-zones/list_network_zones?id="+serverId+"&project=" + project + "&recursion=1",
          dataType: "json",
          dataSrc: "metadata",
          contentType: "application/json",
          error: function (xhr, error, code) {
            console.log(xhr, code);
          }
        },
        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: "Actions", data: function (row, type, set) {
              links = ''
              if (row.hasOwnProperty('name')) {
                links += '<a href="#" onclick=editItem(\''+row.name+'\')><i class="fas fa-edit fa-lg" style="color:#ddd" title="Edit" aria-hidden="true"></i></a>' +
                '&nbsp' + '&nbsp' +
                '<a href="#" onclick=confirmDeleteItem(\''+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 addItem(){
      console.log("Info: adding new item");
      data = $('#addForm').serialize();
      $.post("../api/network-zones/add_network_zone?id="+serverId+"&project="+project, data, function (data) {
        console.log(data)
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function confirmDeleteItem(name){
      console.log("Info: confirming deletion of item " + name);
      $("#deleteQuestionText").text("Are you sure you want to remove the network zone " + name + "?");
      $("#networkZone").val(name);
      $("#deleteModal").modal('show');
    }

    function createItemUsingJSON(){
      var json = $("#jsonCreateInput").val();
      console.log("Info: adding new network zone");
      $.post("../api/network-zones/add_network_zone?id="+serverId+"&project="+project, { json: json },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function deleteItem(){
      name = $("#networkZone").val();
      console.log("Info: deleting item " + name);
      $.post("../api/network-zones/delete_network_zone?id=" + serverId + "&project=" + project, { name: name }, function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function editItem(name){
      editedNetworkZone = name
      console.log("Info: loading network zone " + name);
      $.post("../api/network-zones/load_network_zone?id=" + serverId + "&project=" + project, { name: name }, function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        $("#jsonInput").val(JSON.stringify(data.metadata, null, 2));
        $("#editModal").modal('show');
      });
    }

    function renameItem(){
      name = editedNetworkZone
      console.log("Info: renaming network zone");
      data = $('#renameForm').serialize();
      $.post("../api/network-zones/update_network_zone?id=" + serverId + "&project=" + project + "&name=" + encodeURI(name), data, function (data) {
        console.log(data)
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function updateItem(){
      name = editedNetworkZone
      var updatedJSON = $("#jsonInput").val();
      console.log("Info: updating netowrk zone");
      $.post("../api/network-zones/update_network_zone?id=" + serverId + "&project=" + project + "&name=" + encodeURI(name), { json: updatedJSON },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    $(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 %}