{% 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 Network ACL Rule" aria-hidden="true">
        <i class="fas fa-plus fa-sm fa-fw"></i> Network ACL Rule
      </a>
    </div>
  </div>
{% endblock header %}

{% block content %}
  <div class="col-12">
    <ul class="nav nav-tabs" id="myTab" role="tablist">
      <li class="nav-item">
        <a class="nav-link active" id="ingress-tab" data-toggle="tab" href="#ingress" role="tab" aria-controls="ingress" aria-selected="true">Ingress</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" id="egress-tab" data-toggle="tab" href="#egress" role="tab" aria-controls="egress" aria-selected="false">Egress</a>
      </li>
    </ul>

    <div class="tab-content" id="myTabContent">
      <div class="tab-pane fade show active" id="ingress" role="tabpanel" aria-labelledby="ingress-tab">
        <br />
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">Ingress</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">
            <div class="table-responsive">
              <table class="table" id="myDataTable" width="100%" cellspacing="0">
              </table>
            </div>
          </div>
        </div>
      </div>
      <div class="tab-pane fade" id="egress" role="tabpanel" aria-labelledby="egress-tab">
        <br />
        <div class="card">
          <div class="card-header">
            <h3 class="card-title">Egress</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">
            <div class="table-responsive">
              <table class="table" id="myDataTable2" width="100%" cellspacing="0">
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>
{% endblock content %}

{% block modal %}
  {% include 'modals/network-acl.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');
    const acl = urlParams.get('acl')
    var editedNetworkACL = ''
    applySidebarStyles();
    applySidebarLinks();
    populateSidebarLinks();
    populateNavbarLinks();

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

      //Reload the datatables content
      $('#myDataTable').DataTable().ajax.reload(null, false);
      $('#myDataTable2').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, 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>');
        }
      })

      //Get data using jquery call datatable within function, set data: data.ingress for one table and data.exgress for the other
      $('#myDataTable').DataTable({
        ajax: {
          url: "../api/network-acl/list_network_acls?id="+serverId+"&project=" + project + "&acl=" + acl,
          dataType: "json",
          dataSrc: "metadata.ingress",
          contentType: "application/json"
        },
        columns: [
          { title: "Index", data: function (row, type, set) {
              return row.index
            }
          },
          { title: "Action", data: function (row, type, set) {
              if (row.hasOwnProperty('action')) {
                if (row.action)
                  return row.action
              }
              return '-'
            },
          },
          { title: "State", data: function (row, type, set) {
              if (row.hasOwnProperty('state')) {
                if (row.state)
                  return row.state
              }
              return '-'
            },
          },
          { title: "Description", data: function (row, type, set) {
              if (row.hasOwnProperty('description')) {
                if (row.description)
                  return row.description
              }
              return '-'
            },
          },
          { title: "Source", data: function (row, type, set) {
              if (row.hasOwnProperty('source')) {
                if (row.source)
                  return row.source
              }
              return '-'
            },
          },
          { title: "Destination", data: function (row, type, set) {
              if (row.hasOwnProperty('destination')) {
                if (row.destination)
                  return row.destination
              }
              return '-'
            },
          },
          { title: "Protocol", data: function (row, type, set) {
              if (row.hasOwnProperty('protocol')) {
                if (row.protocol)
                  return row.protocol
              }
              return '-'
            },
          },
          { title: "Source Port", data: function (row, type, set) {
              if (row.hasOwnProperty('source_port')) {
                if (row.source_port)
                  return row.source_port
              }
              return '-'
            },
          },
          { title: "Destination Port", data: function (row, type, set) {
              if (row.hasOwnProperty('destination_port')) {
                if (row.destination_port)
                  return row.destination_port
              }
              return '-'
            },
          },
          { title: "ICMP Type", data: function (row, type, set) {
              if (row.hasOwnProperty('icmp_type')) {
                if (row.icmp_type)
                  return row.icmp_type
              }
              return '-'
            },
          },
          { title: "ICMP Code", data: function (row, type, set) {
              if (row.hasOwnProperty('icmp_code')) {
                if (row.icmp_code)
                  return row.icmp_code
              }
              return '-'
            },
          },
          { title: "Actions", data: function (row, type, set) {
              links = '<a href="#" onclick=confirmDeleteItem(\''+row.index+'\',\'ingress\')><i class="fas fa-trash-alt fa-lg" style="color:#ddd" title="Delete" aria-hidden="true"></i></a>'
              return links
            },
          },
        ],
        order: [],
      });

      $('#myDataTable2').DataTable({
        ajax: {
          url: "../api/network-acl/list_network_acls?id="+serverId+"&project=" + project + "&acl=" + acl,
          dataType: "json",
          dataSrc: "metadata.egress",
          contentType: "application/json"
        },
        columns: [
          { title: "Index", data: function (row, type, set) {
              return row.index
            },
          },
          { title: "Action", data: function (row, type, set) {
              if (row.hasOwnProperty('action')) {
                if (row.action)
                  return row.action
              }
              return '-'
            },
          },
          { title: "State", data: function (row, type, set) {
              if (row.hasOwnProperty('state')) {
                if (row.state)
                  return row.state
              }
              return '-'
            },
          },
          { title: "Description", data: function (row, type, set) {
              if (row.hasOwnProperty('description')) {
                if (row.description)
                  return row.description
              }
              return '-'
            },
          },
          { title: "Source", data: function (row, type, set) {
              if (row.hasOwnProperty('source')) {
                if (row.source)
                  return row.source
              }
              return '-'
            },
          },
          { title: "Destination", data: function (row, type, set) {
              if (row.hasOwnProperty('destination')) {
                if (row.destination)
                  return row.destination
              }
              return '-'
            },
          },
          { title: "Protocol", data: function (row, type, set) {
              if (row.hasOwnProperty('protocol')) {
                if (row.protocol)
                  return row.protocol
              }
              return '-'
            },
          },
          { title: "Source Port", data: function (row, type, set) {
              if (row.hasOwnProperty('source_port')) {
                if (row.source_port)
                  return row.source_port
              }
              return '-'
            },
          },
          { title: "Destination Port", data: function (row, type, set) {
              if (row.hasOwnProperty('destination_port')) {
                if (row.destination_port)
                  return row.destination_port
              }
              return '-'
            },
          },
          { title: "ICMP Type", data: function (row, type, set) {
              if (row.hasOwnProperty('icmp_type')) {
                if (row.icmp_type)
                  return row.icmp_type
              }
              return '-'
            },
          },
          { title: "ICMP Code", data: function (row, type, set) {
              if (row.hasOwnProperty('icmp_code')) {
                if (row.icmp_code)
                  return row.icmp_code
              }
              return '-'
            },
          },
          { title: "Actions", data: function (row, type, set) {
              links = '<a href="#" onclick=confirmDeleteItem(\''+row.index+'\',\'egress\')><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 network-acl");
      data = $('#addForm').serialize();
      $.post("../api/network-acl/add_network_acl?id="+serverId+"&project="+project+"&acl="+acl, data, function (data) {
        console.log(data)
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        setTimeout(() => { reloadPageContent(); }, 1000);
        operationStatusCheck()
      });
    }

    function confirmDeleteItem(name, type){
      console.log("Info: confirming deletion of network-acl " + name);
      if (confirm("Are you sure you want to delete network-acl " + name + "?") == true) {
        deleteItem(name, type);
      }
    }

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

    function deleteItem(name, type){
      console.log("Info: deleting network-acl " + name);
      $.post("../api/network-acl/delete_network_acl?id=" + serverId + "&project=" + project+"&acl="+acl, { index: name, type: type }, 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 if (!acl) {
        window.location.href = '../network-acls?id=' + serverId + '&project=' + project
      }
      else {
        loadPageContent()
        operationStatusCheck()
      }
 
    });

  </script>
{% endblock script %}