extends layout

block content
  include ./includes/common.pug
  script.
    function generateLengthMenu(setting_txPerPage, lengthMenuOpts) {
      var addedLength = false;
      for (i = 0; i < lengthMenuOpts.length; i++) {
        if (!addedLength) {
          if (lengthMenuOpts[i] > setting_txPerPage) {
            lengthMenuOpts.splice(i, 0, setting_txPerPage);
            addedLength = true;
          } else if (lengthMenuOpts[i] == setting_txPerPage)
            addedLength = true;
        }
      }
      if (!addedLength && setting_txPerPage != lengthMenuOpts[lengthMenuOpts.length - 1])
        lengthMenuOpts.push(setting_txPerPage);
      return lengthMenuOpts;
    }
    $(document).ready(function() {
      $.ajax({
        method: 'GET',
        url: '/ext/getnetworkpeers/internal',
        dataType: 'json'
      }).done(function(peers) {
        var setting_txPerPage = parseInt("#{settings.network_page.connections_table.items_per_page}");
        var setting_con_port_filter = "#{settings.network_page.connections_table.port_filter}";
        var setting_con_hide_protocols = !{JSON.stringify(settings.network_page.connections_table.hide_protocols)};
        var connectionRows = JSON.parse(JSON.stringify(peers));

        if (setting_con_port_filter == null || setting_con_port_filter == '')
          setting_con_port_filter = '-1';

        setting_con_hide_protocols.forEach(function (protocol) {
          connectionRows = connectionRows.filter(v => v.protocol != protocol);
        });

        if (parseInt(setting_con_port_filter) > 0)
          connectionRows = connectionRows.filter(v => v.port == setting_con_port_filter);
        else if (setting_con_port_filter == '-1') {
          // remove port key
          connectionRows.forEach(function(obj) {
            delete obj.port
          });

          // remove duplicate rows by ip address
          connectionRows = connectionRows.filter((v, i, a) => a.findIndex(t => (t.address === v.address)) === i);
        }

        var columns = [];

        if (setting_con_port_filter == '-1') {
          columns = [
            { data: 'address', width: '25%' },
            { data: 'protocol', width: '25%' },
            { data: 'version', width:'25%' },
            { data: 'country', width: '25%'}
          ];
        } else {
          columns = [
            { data: 'address', width: '20%' },
            { data: 'port', width: '20%' },
            { data: 'protocol', width: '20%' },
            { data: 'version', width:'20%' },
            { data: 'country', width: '20%'}
          ];
        }

        $('#connections-table').dataTable({
          autoWidth: true,
          searching: false,
          ordering: true,
          order: [],
          responsive: true,
          lengthChange: true,
          processing: true,
          iDisplayLength: setting_txPerPage,
          lengthMenu: generateLengthMenu(setting_txPerPage, !{JSON.stringify(settings.network_page.connections_table.page_length_options)}),
          scrollX: true,
          language: {
            paginate: {
              previous: '<',
              next: '>'
            }
          },
          data: connectionRows,
          rowCallback: function (row, data, index) {
            var colIndex = 1;
            var flagBlock = '';

            if (data['country_code'].length > 1) {
              flagBlock = '<div class="margin-left-5 flag-icon flag-icon-'+data['country_code'].toLowerCase()+'"></div>';
            }

            $("td:eq(0)", row).html(data['address']).addClass('breakWord');

            if (setting_con_port_filter != '-1') {
              $("td:eq(1)", row).html(data['port']);
              colIndex = 2;
            }

            $(`td:eq(${colIndex})`, row).html(data['protocol']);
            $(`td:eq(${colIndex + 1})`, row).html(data['version']);
            $(`td:eq(${colIndex + 2})`, row).html(data['country'] + flagBlock);
          },
          fnDrawCallback: function(settings) {
            fixDataTableColumns();
            fixFooterHeightAndPosition();
          },
          columns: columns
        });

        setting_txPerPage = parseInt("#{settings.network_page.addnodes_table.items_per_page}");

        var addNodeRows = [];
        var setting_add_port_filter = "#{settings.network_page.addnodes_table.port_filter}";
        var setting_add_hide_protocols = !{JSON.stringify(settings.network_page.addnodes_table.hide_protocols)};
        var addNodePeers = JSON.parse(JSON.stringify(peers));

        if (setting_add_port_filter == null || setting_add_port_filter == '')
          setting_add_port_filter = '-1';

        setting_add_hide_protocols.forEach(function (protocol) {
          addNodePeers = addNodePeers.filter(v => v.protocol != protocol);
        });

        if (parseInt(setting_add_port_filter) > 0)
          addNodePeers = addNodePeers.filter(v => v.port == setting_add_port_filter);
        else if (setting_add_port_filter == '-1') {
          // remove port key
          addNodePeers.forEach(function(obj) {
            delete obj.port
          });

          // remove duplicate rows by ip address
          addNodePeers = addNodePeers.filter((v, i, a) => a.findIndex(t => (t.address === v.address)) === i);
        }

        for (var i = 0; i < addNodePeers.length; i++)
          addNodeRows.push({'nodes': 'addnode=' + (addNodePeers[i]['address'] != null && addNodePeers[i]['address'].indexOf(':') > -1 ? '[' + addNodePeers[i]['address'] + ']' : addNodePeers[i]['address']) + (addNodePeers[i]['port'] == null ? '' : ':' + addNodePeers[i]['port'])});

        $('#addnodes-table').dataTable({
          autoWidth: true,
          searching: false,
          ordering: false,
          responsive: true,
          lengthChange: true,
          processing: true,
          iDisplayLength: setting_txPerPage,
          lengthMenu: generateLengthMenu(setting_txPerPage, !{JSON.stringify(settings.network_page.addnodes_table.page_length_options)}),
          scrollX: true,
          language: {
            paginate: {
              previous: '<',
              next: '>'
            }
          },
          data: addNodeRows,
          rowCallback: function(row, data, index) {
            $("td:eq(0)", row).css('white-space', 'nowrap').html(`<button class="btn btn-sm btn-copy" type="button"><i class="far fa-copy"></i></button>&nbsp;<span>${data.nodes}</span>`);
          },
          fnDrawCallback: function(settings) {
            fixDataTableColumns();
            fixFooterHeightAndPosition();
          },
          columns: [
            {data: 'nodes', width: '100%'}
          ],
          columnDefs: [
            {targets: '_all', className: 'text-start'}
          ]
        });

        setting_txPerPage = parseInt("#{settings.network_page.onetry_table.items_per_page}");

        var oneTryRows = [];
        var setting_one_port_filter = "#{settings.network_page.onetry_table.port_filter}";
        var setting_one_hide_protocols = !{JSON.stringify(settings.network_page.onetry_table.hide_protocols)};

        if (setting_one_port_filter == null || setting_one_port_filter == '')
          setting_one_port_filter = '-1';

        setting_one_hide_protocols.forEach(function (protocol) {
          peers = peers.filter(v => v.protocol != protocol);
        });

        if (parseInt(setting_one_port_filter) > 0)
          peers = peers.filter(v => v.port == setting_one_port_filter);
        else if (setting_one_port_filter == '-1') {
          // remove port key
          peers.forEach(function(obj) {
            delete obj.port
          });

          // remove duplicate rows by ip address
          peers = peers.filter((v, i, a) => a.findIndex(t => (t.address === v.address)) === i);
        }

        for (var i=0; i < peers.length; i++)
          oneTryRows.push({'nodes': 'addnode ' + (peers[i]['address'] != null && peers[i]['address'].indexOf(':') > -1 ? '[' + peers[i]['address'] + ']' : peers[i]['address']) + (peers[i]['port'] == null ? '' : ':' + peers[i]['port']) + ' onetry'});

        $('#onetry-table').dataTable({
          autoWidth: true,
          searching: false,
          ordering: false,
          responsive: true,
          lengthChange: true,
          processing: true,
          iDisplayLength: setting_txPerPage,
          lengthMenu: generateLengthMenu(setting_txPerPage, !{JSON.stringify(settings.network_page.onetry_table.page_length_options)}),
          scrollX: true,
          language: {
            paginate: {
              previous: '<',
              next: '>'
            }
          },
          data: oneTryRows,
          rowCallback: function(row, data, index) {
            $("td:eq(0)", row).css('white-space', 'nowrap').html(`<button class="btn btn-sm btn-copy" type="button"><i class="far fa-copy"></i></button>&nbsp;<span>${data.nodes}</span>`);
          },
          fnDrawCallback: function(settings) {
            fixDataTableColumns();
            fixFooterHeightAndPosition();
          },
          columns: [
            {data: 'nodes', width: '100%'}
          ],
          columnDefs: [
            {targets: '_all', className: 'text-start'}
          ]
        });
      });

      $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function (e) {
        fixDataTableColumns();
        fixFooterHeightAndPosition();
      });

      if ('#{settings.network_page.page_header.show_last_updated}' == 'true') {
        var lastUpdatedDate = #{(last_updated == null || last_updated == '0' ? 0 : last_updated)};

        if (lastUpdatedDate != 0) {
          $('span#lastUpdatedDate').html(' ' + format_unixtime(lastUpdatedDate));

          if (#{settings.shared_pages.date_time.enable_alt_timezone_tooltips} == true) {
            $('span#lastUpdatedDate').attr('data-bs-toggle', 'tooltip').attr('data-bs-placement', 'auto').attr('title', format_unixtime(lastUpdatedDate, true));
            enableTooltips();
          }
        } else
          $('span#lastUpdatedDate').html(' N/A');
      }
      if (#{settings.shared_pages.page_header.page_title_image.enable_animation} == true && #{settings.network_page.page_header.show_img} == true)
        startRotateElement('img#header-img');

      $('#addnodes').on('click', 'button.btn-copy', function (event) {
        var btn = $(this);

        if (btn.html().indexOf('fa-copy') > -1) {
          var tmp = $('<input>');
          $('body').append(tmp);
          tmp.val(btn.parent().find('span').html()).select();
          document.execCommand('copy');
          tmp.remove();

          btn.tooltip({title: 'Copied!', placement: 'top', trigger: 'manual'}).tooltip('show');
          btn.html('<i class="fas fa-check"></i>');

          setTimeout(function() {
            btn.html('<i class="far fa-copy"></i>');
            btn.tooltip('dispose');
          }, 1500);
        }
      });
    });
  - var theadClasses = [];
  if settings.shared_pages.table_header_bgcolor != null && settings.shared_pages.table_header_bgcolor != ''
    - theadClasses.push('table-' + settings.shared_pages.table_header_bgcolor);
  .col-md-12.cardSpacer
    .container
      if settings.network_page.page_header.show_img == true || settings.network_page.page_header.show_title == true || settings.network_page.page_header.show_last_updated == true || settings.network_page.page_header.show_description == true
        #page-header-container(style='align-items:' + (settings.network_page.page_header.show_img == true && settings.network_page.page_header.show_title == true && settings.network_page.page_header.show_last_updated == true && settings.network_page.page_header.show_description == true ? 'flex-start' : 'center'))
          if settings.network_page.page_header.show_img == true
            #header-img-container
              img#header-img(src=(settings.shared_pages.page_header.page_title_image == null || settings.shared_pages.page_header.page_title_image.image_path == null || settings.shared_pages.page_header.page_title_image.image_path == '' ? '/img/page-title-img.png' : settings.shared_pages.page_header.page_title_image.image_path))
          #page-title-container
            if settings.network_page.page_header.show_title == true
              h3#page-title #{settings.locale.net_title.replace('{1}', settings.coin.name)}
            if settings.network_page.page_header.show_last_updated == true
              if settings.network_page.page_header.show_title != true && settings.network_page.page_header.show_description != true
                #page-title-container
                  .sub-page-header
                    span.fw-bold=settings.locale.last_updated + ':'
                    span.text-muted#lastUpdatedDate
              else
                .sub-page-header(style='margin-bottom:' + (settings.network_page.page_header.show_description == true ? '5' : '0') + 'px')
                  span.fw-bold=settings.locale.last_updated + ':'
                  span.text-muted#lastUpdatedDate
            if settings.network_page.page_header.show_description == true
              if settings.network_page.page_header.show_title != true && settings.network_page.page_header.show_last_updated != true
                #page-title-container
                  .sub-page-header.text-muted=settings.locale.net_description.replace('{1}', settings.coin.name)
              else
                .sub-page-header.text-muted=settings.locale.net_description.replace('{1}', settings.coin.name)
        .cardSpacer.clearfix
      ul.nav.nav-tabs(role='tablist')
        li.nav-item(role='presentation')
          a.nav-link.active(href='#connections', aria-controls='connections', role='tab', data-bs-toggle='tab') #{settings.locale.net_connections}
        li.nav-item(role='presentation')
          a.nav-link(href='#addnodes', aria-controls='addnodes', role='tab', data-bs-toggle='tab') #{settings.locale.net_addnodes}
    .tab-content
      #connections.container.tab-pane.active(style='margin-top:0;border-top:0;')
        .card.card-default.border-0
          table#connections-table.table.table-bordered.table-striped.table-paging.table-hover.mobile-border-right
            thead
              tr(class=theadClasses)
                th.text-center #{settings.locale.net_address}
                if settings.network_page.connections_table.port_filter != '-1'
                  th.text-center='Port'
                th.text-center #{settings.locale.net_protocol}
                th.text-center #{settings.locale.net_subversion}
                th.text-center #{settings.locale.net_country}
            tbody.text-center
      #addnodes.container.tab-pane(style='margin-top:0;border-top:0;')
        .card.card-default.border-0
          .card-body.border-top-0
            p If you have trouble syncing your wallet, add these lines to your coin daemon .conf file and restart the wallet.
            p
              em Typically you can access the config file through QT-wallet menu, Tools > Open Wallet Configuration File
          table#addnodes-table.table.table-bordered.table-striped.table-paging.table-hover.mobile-border-right
            thead
              tr(class=theadClasses)
                th AddNode Config Lines
            tbody
          .card-body.border-top-0
            p="Alternatively you can try one of these lines in the coin wallet debug window, or add them with" + " "
              em coindaemon-cli
          table#onetry-table.table.table-bordered.table-striped.table-paging.table-hover.mobile-border-right
            thead
              tr(class=theadClasses)
                th OneTry Node Lines
            tbody