/*
 * Copyright (c) 2018, FusionAuth, All Rights Reserved
 */
'use strict';
var FusionAuth = FusionAuth || {};
FusionAuth.Admin = FusionAuth.Admin || {};

/**
 * Handles User Search page.
 *
 * @constructor
 */
FusionAuth.Admin.UserSearch = function(queryString) {
  Prime.Utils.bindAll(this);

  this.form = Prime.Document.queryById('user-search-form');
  new FusionAuth.UI.AdvancedControls(this.form, 'io.fusionauth.userSearch.advancedControls').initialize();

  // Global Bulk Actions
  Prime.Document.query('.bulk-actions a[data-ajax-form="true"]').addEventListener('click', this._handleAddRemoverMembersClick);

  if (queryString !== null) {
    history.replaceState({}, '', FusionAuth.requestContextPath + '/admin/user/');
  }

  new FusionAuth.Admin.AdvancedUserSearch(this.form, queryString).search();
};

FusionAuth.Admin.UserSearch.prototype = {

  /* ===================================================================================================================
   * Private methods
   * ===================================================================================================================*/

  _handleAddRemoverMembersClick: function(event) {
    Prime.Utils.stopEvent(event);
    var button = new Prime.Document.Element(event.currentTarget);
    var uri = button.getAttribute('href');

    var data = {'userIds': []};
    var table = Prime.Document.queryFirst('[data-user-table]');
    table.query('tbody input[type="checkbox"]:checked').each(function(e) {
      data.userIds.push(e.getValue());
    });

    new Prime.Widgets.AJAXDialog()
        .withFormHandling(true)
        .withAdditionalClasses(button.is('[data-ajax-wide-dialog=true]') ? 'wide' : '')
        .withAjaxRequest(new Prime.Ajax.Request(uri, 'POST').withJSON(data))
        .open(uri);
  }
};
