{% extends "main.html" %}

{% block header %}
  <div class="row mb-2">
    <div class="col-sm-6">
      <h1>{{ page_title | safe }} <span id="network_title"></span></h1>
    </div>
    <div class="col-sm-6">

      <a class="btn btn-outline-primary dropdown-toggle float-sm-right ml-2 mr-4" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" title="Actions">
        Network Actions
      </a>
      <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
        <a class="dropdown-item text-primary" href="#" data-toggle="modal" data-target="#addLoadBalancerModal" id="addLoadBalancer"><i class="fas fa-save fa-sm fa-fw mr-2"></i>Add Load Balancer</a>
        <a class="dropdown-item text-primary" href="#" data-toggle="modal" data-target="#addForwardModal" id="addForward"><i class="fas fa-save fa-sm fa-fw mr-2"></i>Add Forward</a>
        <a class="dropdown-item text-primary" href="#" data-toggle="modal" data-target="#addPeerModal" id="addPeer"><i class="fas fa-save fa-sm fa-fw mr-2"></i>Add Peer</a>
      </div>

    </div>
  </div>
{% endblock header %}

{% block content %}
  <div class="col-12">

    <nav>
      <div class="nav nav-tabs" id="nav-page-tab" role="tablist">
        <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Home</a>
        <a class="nav-item nav-link" id="nav-forwards-tab" data-toggle="tab" href="#nav-forwards" role="tab" aria-controls="nav-forwards" aria-selected="false">Forwards</a>
        <a class="nav-item nav-link" id="nav-load-balancers-tab" data-toggle="tab" href="#nav-load-balancers" role="tab" aria-controls="nav-load-balancers" aria-selected="false">Load Balancers</a>
        <a class="nav-item nav-link" id="nav-peers-tab" data-toggle="tab" href="#nav-peers" role="tab" aria-controls="nav-peers" aria-selected="false">Peers</a>
      </div>
    </nav>
    <div class="tab-content" id="nav-page-content">
      <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        <br />
        <div class="row">
          <div class="col-9">
      
            <!-- DHCP Leases Card-->
            <div class="card" id="dhcpLeasesCard">
              <div class="card-header">
                <h3 class="card-title text-primary" data-card-widget="collapse">
                    DHCP Leases
                </h3>
                <div class="card-tools">
                  <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                </div>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-hover" id="dhcpLeasesTable" width="100%" cellspacing="0">
                  </table>
                </div>
              </div>
            </div>
    
          </div>

          <div class="col-3">
      
            <div class="accordion" id="accordionExample">
      
              <!-- Network State Card-->
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title text-primary" data-card-widget="collapse">
                    Network State
                  </h3>
                  <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                  </div>
                </div>
                <div class="card-body">
                  <table class="table table-sm h6">
                    <tr><td class="pr-3">HWAddr:</td> <td><span id="hwaddr">-</span></td></tr>
                    <tr><td class="pr-3">MTU:</td> <td><span id="mtu">-</span></td></tr>
                    <tr><td class="pr-3">State:</td> <td><span id="state">-</span></td></tr>
                    <tr><td class="pr-3">Type:</td> <td><span id="type">-</span></td></tr>
                    <tr><td class="pr-3">Bond:</td> <td><span id="bond">-</span></td></tr>
                    <tr><td class="pr-3">OVN:</td> <td><span id="ovn">-</span></td></tr>
                    <tr><td class="pr-3">VLAN:</td> <td><span id="vlan">-</span></td></tr>
                  </table>
                </div>
              </div>

              <!-- Network Counters Card-->
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title text-primary" data-card-widget="collapse">
                    Network Counters
                  </h3>
                  <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                  </div>
                </div>
                <div class="card-body">
                  <table class="table table-sm h6">
                    <tr><td class="pr-3">bytes_received:</td> <td><span id="counters_bytes_received">-</span></td></tr>
                    <tr><td class="pr-3">bytes_sent:</td> <td><span id="counters_bytes_sent">-</span></td></tr>
                    <tr><td class="pr-3">packets_received:</td> <td><span id="packets_bytes_received">-</span></td></tr>
                    <tr><td class="pr-3">packets_sent:</td> <td><span id="packets_bytes_sent">-</span></td></tr>
                  </table>
                </div>
              </div>

              <!-- Network Bridge Card-->
              <div class="card">
                <div class="card-header">
                  <h3 class="card-title text-primary" data-card-widget="collapse">
                    Network Bridge
                  </h3>
                  <div class="card-tools">
                    <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                  </div>
                </div>
                <div class="card-body">
                  <table class="table table-sm h6">
                    <tr><td class="pr-3">forward_delay:</td> <td><span id="bridge_forward_delay">-</span></td></tr>
                    <tr><td class="pr-3">id:</td> <td><span id="bridge_id">-</span></td></tr>
                    <tr><td class="pr-3">stp:</td> <td><span id="bridge_stp">-</span></td></tr>
                    <tr><td class="pr-3">upper_devices:</td> <td><span id="bridge_upper_devices">-</span></td></tr>
                    <tr><td class="pr-3">vlan_default:</td> <td><span id="bridge_vlan_default">-</span></td></tr>
                    <tr><td class="pr-3">vlan_filtering:</td> <td><span id="bridge_vlan_filtering">-</span></td></tr>
                  </table>
                </div>
              </div>
            
            </div>
          </div>

        </div>
      </div>
      <div class="tab-pane fade" id="nav-forwards" role="tabpanel" aria-labelledby="nav-forwards-tab">
        <br />
        <div class="col-12">
          <!-- Forwards Card-->
          <div class="card" id="forwardsCard">
            <div class="card-header">
              <h3 class="card-title text-primary" data-card-widget="collapse">
                Network Forwards <span class="text-secondary small">(Available only on Bridge or OVN networks)</span>
              </h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <i class="fa fa-bars"></i>
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <a href="#" class="dropdown-item" data-toggle="modal" data-target="#addForwardModal" title="Create Forward">Create Forward</a>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-hover" id="forwardsTable" width="100%" cellspacing="0">
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div class="tab-pane fade" id="nav-load-balancers" role="tabpanel" aria-labelledby="nav-load-balancers-tab">
        <br />
        <div class="col-12">
          <!-- Load Balancers Card-->
          <div class="card" id="loadBalancersCard">
            <div class="card-header">
              <h3 class="card-title text-primary" data-card-widget="collapse">
                Network Load Balancers <span class="text-secondary small">(Available only on OVN networks)</span>
              </h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
                <button type="button" class="btn btn-tool" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <i class="fa fa-bars"></i>
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <a href="#" class="dropdown-item" data-toggle="modal" data-target="#addLoadBalancerModal" title="Create Load Balancer">Create Load Balancer</a>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-hover" id="loadBalancersTable" width="100%" cellspacing="0">
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div class="tab-pane fade" id="nav-peers" role="tabpanel" aria-labelledby="nav-peers-tab">
        <br />
        <div class="col-12">
          <!-- Peers Card-->
          <div class="card" id="peersCard">
            <div class="card-header">
              <h3 class="card-title text-primary" data-card-widget="collapse">
                Network Peers <span class="text-secondary small">(Available only on OVN networks)</span>
              </h3>
              <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-plus"></i></button>
                <button type="button" class="btn btn-tool" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                  <i class="fa fa-bars"></i>
                </button>
                <div class="dropdown-menu dropdown-menu-right">
                  <a href="#" class="dropdown-item" data-toggle="modal" data-target="#addPeerModal" title="Create Peer">Create Peer</a>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-hover" id="peersTable" width="100%" cellspacing="0">
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
{% endblock content %}

{% block modal %}
  {% include 'modals/network.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 network = urlParams.get('network');
    const network_type = urlParams.get('network_type');
    var editedNetwork

    populateSidebarLinks();
    populateNavbarLinks();
    applySidebarStyles();
    applySidebarLinks();

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

      //Load Network State
      loadNetworkState()

      loadDhcpLeasesTable()
      loadLoadBalancersTable()
      loadForwardsTable()
      loadPeersTables()

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

    function loadPageContent(){
      
      //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>');
        }
      })

      //Load Network State
      loadNetworkState()

      //Load Tables
      loadDhcpLeasesTable()
      loadLoadBalancersTable()
      loadForwardsTable()
      loadPeersTables()

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

    }


    function loadNetworkState() {
      $.get("../api/network/get_network_state?id="+serverId+"&project="+project+"&name="+network+"&recursion=1", function (data) {

        data = data.metadata;
        console.log(data)

        if (data.hasOwnProperty('hwaddr') && data.hwaddr) { $("#hwaddr").text(data.hwaddr); }
        if (data.hasOwnProperty('mtu') && data.mtu) { $("#mtu").text(data.mtu); }
        if (data.hasOwnProperty('state') && data.state) { $("#state").text(data.state); }
        if (data.hasOwnProperty('type') && data.type) { $("#type").text(data.type); }
        if (data.hasOwnProperty('bond') && data.bond) { $("#bond").text(data.bond); }
        if (data.hasOwnProperty('ovn') && data.ovn) { $("#ovn").text(data.ovn); }
        if (data.hasOwnProperty('vlan') && data.vlan) { $("#vlan").text(data.vlan); }

        if (data.hasOwnProperty('counters') && data.counters){
          dataCounters = data.counters;
          if (dataCounters.hasOwnProperty('bytes_received') && dataCounters.bytes_received) { $("#counters_bytes_received").text(dataCounters['bytes_received']); }
          if (dataCounters.hasOwnProperty('bytes_sent') && dataCounters.bytes_sent) { $("#counters_bytes_sent").text(dataCounters['bytes_sent']); }
          if (dataCounters.hasOwnProperty('packets_received') && dataCounters.packets_received) { $("#packets_bytes_received").text(dataCounters['packets_received']); }
          if (dataCounters.hasOwnProperty('packets_sent') && dataCounters.packets_sent) { $("#packets_bytes_sent").text(dataCounters['packets_sent']); }
        }

        if (data.hasOwnProperty('bridge') && data.bridge){
          dataBridge = data.bridge;
          if (dataBridge.hasOwnProperty('forward_delay') && dataBridge.forward_delay) { $("#bridge_forward_delay").text(dataBridge['forward_delay']); }
          if (dataBridge.hasOwnProperty('id') && dataBridge.id) { $("#bridge_id").text(dataBridge['id']); }
          if (dataBridge.hasOwnProperty('stp')) { $("#bridge_stp").text(dataBridge['stp']); } //Boolean
          if (dataBridge.hasOwnProperty('upper_devices') && dataBridge.upper_devices) { $("#bridge_upper_devices").text(dataBridge['upper_devices'].join(', ')); } //Array
          if (dataBridge.hasOwnProperty('id') && dataBridge.id) { $("#bridge_id").text(dataBridge['id']); }
          if (dataBridge.hasOwnProperty('vlan_default') && dataBridge.vlan_default) { $("#bridge_vlan_default").text(dataBridge['vlan_default']); }
          if (dataBridge.hasOwnProperty('vlan_filtering') && dataBridge.vlan_filtering) { $("#bridge_vlan_filtering").text(dataBridge['vlan_filtering']); }
        }

        });
    }

    function loadDhcpLeasesTable() {
      if ( ! $.fn.DataTable.isDataTable( '#dhcpLeasesTable' ) ) {
        //Load DHCP Leases Table
        $('#dhcpLeasesTable').DataTable({
          ajax: {
            url: "../api/network/list_network_leases?id="+serverId+"&project="+project+"&name="+network,
            dataType: "json",
            dataSrc: "metadata",
            contentType: "application/json"
          },
          rowId: 'id',
          stateSave: true,
          columns: [
            { title: "Address", data: function (row, type, set) {
                if (row.hasOwnProperty('address')) {
                  if (row.address)
                    return row.address
                }
                return '-'
              },
            },
            { title: "Hostname", data: function (row, type, set) {
                if (row.hasOwnProperty('hostname')) {
                  if (row.hostname)
                    return row.hostname
                }
                return '-'
              },
            },
            { title: "HWAddr", data: function (row, type, set) {
                if (row.hasOwnProperty('hwaddr')) {
                  if (row.hwaddr)
                    return row.hwaddr
                }
                return '-'
              },
            },
            { title: "Location", data: function (row, type, set) {
                if (row.hasOwnProperty('location')) {
                  if (row.location)
                    return row.location
                }
                return '-'
              },
            },
            { title: "Type", data: function (row, type, set) {
                if (row.hasOwnProperty('type')) {
                  if (row.type)
                    return row.type
                }
                return '-'
              },
            },
          ],
          order: [],
        });
      }
      else {
        $('#dhcpLeasesTable').DataTable().ajax.reload(null, false);
      }
    }

    function loadLoadBalancersTable(){
      if ( ! $.fn.DataTable.isDataTable( '#loadBalancersTable' ) ) {
        //Load Load Balancers Table
        var loadBalancersTable = $('#loadBalancersTable').DataTable({
            ajax: {
              url: "../api/network/list_network_load_balancers?id="+serverId+"&project="+project+"&name="+network+"&recursion=1",
              dataType: "json",
              dataSrc: "metadata",
              contentType: "application/json"
            },
            stateSave: true,
            columns: [
              { title: "Listen Address", data: function (row, type, set) {
                  if (row.hasOwnProperty('listen_address')) {
                    if (row.listen_address)
                      return row.listen_address
                  }
                  return '-'
                },
              },
              { title: "Description", data: function (row, type, set) {
                  if (row.hasOwnProperty('description')) {
                    if (row.description)
                      return row.description
                  }
                  return '-'
                },
              },
              { title: "Location", data: function (row, type, set) {
                  if (row.hasOwnProperty('location')) {
                    if (row.location)
                      return row.location
                  }
                  return '-'
                },
              },
              { title: "Actions", data: function (row, type, set) {
                links = ''
                if (row.hasOwnProperty('listen_address')) {
                  if (row.listen_address){
                    links = '<a href="#" onclick=editLoadBalancer(\''+row.listen_address+'\')><i class="fas fa-edit fa-lg" style="color:#ddd" title="Edit" aria-hidden="true"></i></a>' +
                    '&nbsp' + '&nbsp' +
                    '<a href="#" onclick=deleteItem(\''+row.listen_address+'\',\'load_balancer\')><i class="fas fa-trash-alt fa-lg" style="color:#ddd" title="Delete" aria-hidden="true"></i></a>'
                  }
                }
                return links
              },
            },
            ],
            order: [],
        });
      }
      else {
        $('#loadBalancersTable').DataTable().ajax.reload(null, false);
      }  
    }

    function loadForwardsTable() {
      if ( ! $.fn.DataTable.isDataTable( '#forwardsTable' ) ) {
        //Load Forwards Table
        var forwardsTable = $('#forwardsTable').DataTable({
            ajax: {
              url: "../api/network/list_network_forwards?id="+serverId+"&project="+project+"&name="+network+"&recursion=1",
              dataType: "json",
              dataSrc: "metadata",
              contentType: "application/json"
            },
            stateSave: true,
            columns: [
              { title: "Listen Address", data: function (row, type, set) {
                  if (row.hasOwnProperty('listen_address')) {
                    if (row.listen_address)
                      return row.listen_address
                  }
                  return '-'
                },
              },
              { title: "Description", data: function (row, type, set) {
                  if (row.hasOwnProperty('description')) {
                    if (row.description)
                      return row.description
                  }
                  return '-'
                },
              },
              { title: "Location", data: function (row, type, set) {
                  if (row.hasOwnProperty('location')) {
                    if (row.location)
                      return row.location
                  }
                  return '-'
                },
              },
              { title: "Actions", data: function (row, type, set) {
                links = ''
                if (row.hasOwnProperty('listen_address')) {
                  if (row.listen_address){
                    links = '<a href="#" onclick=editForward(\''+row.listen_address+'\')><i class="fas fa-edit fa-lg" style="color:#ddd" title="Edit" aria-hidden="true"></i></a>' +
                    '&nbsp' + '&nbsp' +
                    '<a href="#" onclick=deleteItem(\''+row.listen_address+'\',\'forward\')><i class="fas fa-trash-alt fa-lg" style="color:#ddd" title="Delete" aria-hidden="true"></i></a>'
                  }
                }
                return links
              },
            },
            ],
            order: [],
        });
      }
      else {
        $('#forwardsTable').DataTable().ajax.reload(null, false);
      }        
    }

    function loadPeersTables() {
      if ( ! $.fn.DataTable.isDataTable( '#peersTable' ) ) {
              //Load Peers Table
        $('#peersTable').DataTable({
          ajax: {
            url: "../api/network/list_network_peers?id="+serverId+"&project="+project+"&name="+network+"&recursion=1",
            dataType: "json",
            dataSrc: "metadata",
            contentType: "application/json"
          },
          rowId: 'id',
          stateSave: true,
          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: "Status", data: function (row, type, set) {
                if (row.hasOwnProperty('status')) {
                  if (row.status)
                    return row.status
                }
                return '-'
              },
            },
            { title: "Target Network", data: function (row, type, set) {
                if (row.hasOwnProperty('target_network')) {
                  if (row.target_network)
                    return row.target_network
                }
                return '-'
              },
            },
            { title: "Target Project", data: function (row, type, set) {
                if (row.hasOwnProperty('target_project')) {
                  if (row.target_project)
                    return row.target_project
                }
                return '-'
              },
            },
            { title: "Actions", data: function (row, type, set) {
              links = ''
              if (row.hasOwnProperty('name')) {
                if (row.name){
                  links = '<a href="#" onclick=editPeer(\''+row.name+'\')><i class="fas fa-edit fa-lg" style="color:#ddd" title="Edit" aria-hidden="true"></i></a>' +
                  '&nbsp' + '&nbsp' +
                  '<a href="#" onclick=deleteItem(\''+row.name+'\',\'peer\')><i class="fas fa-trash-alt fa-lg" style="color:#ddd" title="Delete" aria-hidden="true"></i></a>'
                }
              }
              return links
            },
          },
          ],
          order: [],
        });
      }
      else {
        $('#peersTable').DataTable().ajax.reload(null, false);
      }
    }









    function addItem(type){
      console.log("Info: adding new " + type);
      if (type == 'forward')
        data = $('#addForwardForm').serialize();
      else if (type == 'load_balancer')
        data = $('#addLoadBalancerForm').serialize();
      else if (type == 'peer')
        data = $('#addPeerForm').serialize();
      else
        var json = {}

      $.post("../api/network/add_network_" + type + "?id="+serverId+"&project="+project+"&network="+network, data, function (data) {
        console.log(data)
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function createItemUsingJSON(type){
      console.log("Info: adding new " + type);
      if (type == 'forward')
        var json = $("#jsonCreateForwardInput").val();
      else if (type == 'load_balancer')
        var json = $("#jsonCreateLoadBalancerInput").val();
      else if (type == 'peer')
        var json = $("#jsonCreatePeerInput").val();
      else
        var json = {}
      
      $.post("../api/network/add_network?id="+serverId+"&project="+project+"&network="+network, { json: json },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function deleteItem(name, type){
      console.log("Info: confirming deletion of " + type + " " + name);
      if (confirm("Are you sure you want to delete " + type + " " + name + "?") == true) {
        console.log("Info: deleting " + type + " " + name);
        $.post("../api/network/delete_network_" + type + "?id=" + serverId + "&project=" + project + "&network=" + network, { name: name }, function (data) {
          console.log(data);
          if (data.error_code >= 400){
            alert(data.error);
          }
          //Sync type
          setTimeout(() => { reloadPageContent(); }, 1000);
          operationStatusCheck()
        });
      }
    }

    function editForward(name){
      console.log("Info: loading forward " + name);
      $.post("../api/network/load_network_forward?id=" + serverId + "&project=" + project + "&network=" + network, { name: name }, function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        $("#forwardJsonInput").val(JSON.stringify(data.metadata, null, 2));
        $("#forwardNameHiddenInput").val(name);
        $("#editForwardModal").modal('show');
      });
    }

    function editLoadBalancer(name){
      console.log("Info: loading load balancer " + name);
      $.post("../api/network/load_network_load_balancer?id=" + serverId + "&project=" + project + "&network=" + network, { name: name }, function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        $("#loadBalancerJsonInput").val(JSON.stringify(data.metadata, null, 2));
        $("#loadBalancerNameHiddenInput").val(name);
        $("#editLoadBalancerModal").modal('show');
      });
    }

    function editPeer(name){
      console.log("Info: loading peer " + name);
      $.post("../api/network/load_network_peer?id=" + serverId + "&project=" + project + "&network=" + network, { name: name }, function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        $("#peerJsonInput").val(JSON.stringify(data.metadata, null, 2));
        $("#peerNameHiddenInput").val(name);
        $("#editPeerModal").modal('show');
      });
    }

    function updateForward(){
      var name = $("#forwardNameHiddenInput").val();
      var updatedJSON = $("#forwardJsonInput").val();
      console.log("Info: updating forward " + name);
      $.post("../api/network/update_network_forward?id=" + serverId + "&project=" + project + "&network=" + network + "&name=" + encodeURI(name), { json: updatedJSON },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function updateLoadBalancer(){
      var name = $("#loadBalancerNameHiddenInput").val();
      var updatedJSON = $("#loadBalancerJsonInput").val();
      console.log("Info: updating load balancer " + name);
      $.post("../api/network/update_network_load_balancer?id=" + serverId + "&project=" + project + "&network=" + network + "&name=" + encodeURI(name), { json: updatedJSON },  function (data) {
        console.log(data);
        if (data.error_code >= 400){
          alert(data.error);
        }
        //Sync type
        reloadPageContent();
      });
    }

    function updatePeer(){
      var name = $("#peerNameHiddenInput").val();
      var updatedJSON = $("#peerJsonInput").val();
      console.log("Info: updating peer " + name);
      $.post("../api/network/update_network_peer?id=" + serverId + "&project=" + project + "&network=" + network + "&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 {
        $("#network_title").text(network);
        loadPageContent()
        operationStatusCheck()
      }
    
    });

  </script>


{% endblock script %}