/*
 * Copyright (c) 2018, FusionAuth, All Rights Reserved
 */
'use strict';

var FusionAuth = FusionAuth || {};
FusionAuth.Admin = FusionAuth.Admin || {};

/**
 * Input field with User Search
 *
 * @constructor
 */
FusionAuth.Admin.UserSearchWidget = function(element, hidden) {
  Prime.Utils.bindAll(this);

  this.element = element;
  this.hidden = hidden;

  this._setInitialOptions();
};

FusionAuth.Admin.UserSearchWidget.constructor = FusionAuth.Admin.UserSearchWidget;
FusionAuth.Admin.UserSearchWidget.prototype = {

  getValue: function() {
    if (this.hidden.getValue() !== '') {
      return this.hidden.getValue();
    }

    return null;
  },

  initialize: function() {
    this.inProgress = new Prime.Widgets.InProgress(this.element).withMinimumTime(250);
    new FusionAuth.UI.AutoComplete(this.element)
        .withInputAvailableCallback(this._handleInputCallback)
        .withSelectValueCallback(this._handleSelectValue)
        .withClearValueCallback(this._handleClearInput)
        .initialize();

    return this;
  },

  setValue: function(value) {
    this.hidden.setValue(value);
  },

  withCallback: function(callback) {
    this.options.callback = callback;
    return this;
  },

  withLoginIdValue: function() {
    this.options.loginIdValue = true;
    return this;
  },

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

  _handleClearInput: function() {
    this.hidden.setValue('');
    this.element.setValue('');

    if (this.options.callback) {
      this.options.callback();
    }
  },

  _handleInputCallback: function(value, callback) {
    var searchCriteria = {};
    searchCriteria['s.numberOfResults'] = 50;
    searchCriteria['s.startRow'] = 0;
    searchCriteria['s.queryString'] = value;

    new Prime.Ajax.Request('/ajax/user/search.json', 'GET')
        .withData(searchCriteria)
        .withInProgress(this.inProgress)
        .withSuccessHandler(function(xhr) {
          this._searchSuccessHandler(xhr, callback);
        }.bind(this))
        .withErrorHandler(function(xhr) {
          this._searchErrorHandler(xhr, callback);
        }.bind(this))
        .go();
  },


  _handleSelectValue: function(value, display) {
    this.hidden.setValue(value);
    this.element.setValue(display);
    if (this.options.callback) {
      this.options.callback();
    }
  },

  _searchErrorHandler: function(xhr, callback) {
    callback('<a href="#" class="disabled">  An error occurred, unable to complete search. Status code <em>' + xhr.status + '</em>. </a>')
  },

  _searchSuccessHandler: function(xhr, callback) {
    var json = JSON.parse(xhr.responseText);
    var html = '';

    if (json.total > 0) {
      for (var i=0; i < json['users'].length; i++) {
        var name = json['users'][i].firstName || '';
        if (name) {
          name += ' ';
        }

        name += json['users'][i].lastName || '';
        if (!name) {
          name += json['users'][i].fullName || '';
        }

        var loginId = json['users'][i].email || '';
        if (loginId) {
          name +=  ' &lt;' + loginId + '&gt;';
        } else {
          loginId = json['users'][i].username || '';
          if (loginId) {
            name += ' &lt;' + loginId + '&gt;';
          }
        }

        var dataValue = this.options.loginIdValue ? loginId : json['users'][i].id;
        html += '<a href="#" data-display="' + name + '" data-value="' + dataValue + '">' + name + '</a>';
      }
    } else {
      html += '<a href="#" class="disabled">  No users found  </a>';
    }

    callback(html);
  },

  /**
   * Set the initial options for this widget.
   * @private
   */
  _setInitialOptions() {
    // Defaults
    this.options = {
      callback: null,
      // By default we'll use the userId, set this to true to user the loginId
      loginIdValue: false
    };
  }

};