import $ from 'jquery';

// from https://stackoverflow.com/a/49722514/14601258
// https://github.com/select2/select2/issues/6146#issuecomment-1066034570
import select2 from 'select2';
select2($);

window.enrichPage = function() {
  $('span[data-reverse]').each(function () {
      $(this).load('/admin/tools/reverse?ip=' + $(this).data('reverse'));
  });

  $('[data-toggle="tooltip"]').tooltip({
    trigger: 'hover', // so that tooltips on clicked buttons don't stay shown (for instance copy to clipboard button)
    boundary: 'window', // fixes flickering on some tooltips, see https://stackoverflow.com/a/62076857
  });
}

$(function() {
  enrichPage();

  var loadRequests = {};
  $('[data-load]').each(function () {
    var el = $(this);
    var id = Math.random() * 100;
    var timeout = el.data('timeout');
    var req = $.ajax({
      url: el.data('load'),
      timeout: timeout ? timeout : null,
    })
    .done(function(html) {
      el.html(html);
    })
    .fail(function() {
      el.html('N/A');  
    })
    .always(function() {
      delete loadRequests[id];
    });
    loadRequests[id] = req;
  });
  $(window).on('beforeunload', function () {
    var keys = Object.keys(loadRequests);
    for (var i = 0; i < keys.length; i++) {
      loadRequests[keys[i]].abort();
    }
  });

  $('.select2').select2({
    placeholder: $(this).data('placeholder'),
  });

  $(document).on('click', 'table tr[data-href] a:not([onclick])', function (e) {
    if ($(this).attr('target') == '_blank')
      window.open($(this).attr('href'), '_blank');
    else
      window.location = $(this).attr('href');
    return false;
  });

  $(document).on('click', 'table tr[data-href]', function (e) {
    if (!$(e.target).attr('onclick')) {
      if ($(this).data('target') == '_blank')
        window.open($(this).data('href'), '_blank');
      else
        window.location = $(this).data('href');
      return false;
    }
  });
});