require(['jquery', 'xwiki-events-bridge'], function($) {
  /**
   * Mark disabled and inactive user profiles.
   */
  var maybeMarkDisabled = function(row, rowData) {
    // We use the abstract comparison (!=) because the property value might come as a string.
    if (rowData && rowData.active_value != 1) {
      row.find('td.doc_name').addClass('user disabled');
    }
  };
  // Update the markers when the live table rows are refreshed.
  $(document).on('xwiki:livetable:userdirectory:newrow', function(event, data) {
    maybeMarkDisabled($(data.row), data.data);
  });
  // Initialize the markers. We need this because the 'newrow' event might have been already triggered.
  var usersLiveTable = window['livetable_userdirectory'];
  if (usersLiveTable) {
    $('table#userdirectory tr[data-index]').each(function() {
      var row = $(this);
      var rowData = usersLiveTable.fetchedRows[row.data('index')];
      maybeMarkDisabled(row, rowData);
    });
  }

  /**
   * Live preview when the User Directory settings are modified.
   */
  $('form.user-directory-settings').on('change', function(event) {
    // Default on user-level configuration.
    var configDocument = XWiki.currentDocument;
    if (configDocument.page !== 'UserDirectory' || configDocument.space !== 'Main') {
      // Global configuration.
      configDocument = new XWiki.Document('UserDirectoryConfiguration', 'XWiki');
    }
    var url = configDocument.getURL('get', 'customize=true');
    var data = $(this).serialize();
    var oldLiveTableContainer = $('.xwiki-livetable-container').addClass('loading');
    // We can't use load() here because the live table has in-line script tags that have to be evaluated.
    $.get(url, data).then(html => {
      var newLiveTableContainer = $('<div/>').html(html).find('.xwiki-livetable-container');
      oldLiveTableContainer.replaceWith(newLiveTableContainer);
      $(document).trigger('xwiki:dom:updated', {elements: newLiveTableContainer.toArray()});
    });
  });

  /**
   * User scope filtering (for sub-wikis).
   */
  $('#userScopeFilter').on('change', function(event) {
    var value = $(this).val();
    // The live table is recreated when an user directory setting is changed (live preview) so we can't cache the
    // reference to the live table instance.
    var usersLiveTable = window['livetable_userdirectory'];
    var url = usersLiveTable.getUrl;
    if (url.search('userScope=') >= 0) {
      // Replace the old value.
      if (value === 'local') {
        url = url.replace('userScope=global', 'userScope=local');
      } else {
        url = url.replace('userScope=local', 'userScope=global');
      }
    } else {
      url = url + '&userScope=' + value;
    }
    usersLiveTable.getUrl = url;
    usersLiveTable.refresh();
  });
});
