leteSearch"];

var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var { MailServices } = ChromeUtils.import(
  "resource:///modules/MailServices.jsm"
);

var ACR = Ci.nsIAutoCompleteResult;
var nsIAbAutoCompleteResult = Ci.nsIAbAutoCompleteResult;

// nsAbLDAPAutoCompleteResult
// Derived from nsIAbAutoCompleteResult, provides a LDAP specific result
// implementation.

function nsAbLDAPAutoCompleteResult(aSearchString) {
  // Can't create this in the prototype as we'd get the same array for
  // all instances
  this._searchResults = [];
  this.searchString = aSearchString;
}

nsAbLDAPAutoCompleteResult.prototype = {
  _searchResults: null,
  _commentColumn: "",

  // nsIAutoCompleteResult

  searchString: null,
  searchResult: ACR.RESULT_NOMATCH,
  defaultIndex: -1,
  errorDescription: null,

  get matchCount() {
    return this._searchResults.length;
  },

  getLabelAt(aIndex) {
    return this.getValueAt(aIndex);
  },

  getValueAt(aIndex) {
    return this._searchResults[aIndex].value;
  },

  getCommentAt(aIndex) {
    return this._commentColumn;
  },

  getStyleAt(aIndex) {
    return this.searchResult == ACR.RESULT_FAILURE
      ? "remote-err"
      : "remote-abook";
  },

  getImageAt(aIndex) {
    return "";
  },

  getFinalCompleteValueAt(aIndex) {
    return this.getValueAt(aIndex);
  },

  removeValueAt(aRowIndex, aRemoveFromDB) {},

  // nsIAbAutoCompleteResult

  getCardAt(aIndex) {
    return this._searchResults[aIndex].card;
  },

  // nsISupports

  QueryInterface: ChromeUtils.generateQI([ACR, nsIAbAutoCompleteResult]),
};

function AbLDAPAutoCompleteSearch() {
  Services.obs.addObserver(this, "quit-application");
  this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
}

AbLDAPAutoCompleteSearch.prototype = {
  // A short-lived LDAP directory cache.
  // To avoid recreating components as the user completes, we maintain the most
  // recently used address book, nsAbLDAPDirectoryQuery and search context.
  // However the cache is discarded if it has not been used for a minute.
  // This is done to avoid problems with LDAP sessions timing out and hanging.
  _query: null,
  _book: null,
  _attributes: null,
  _context: -1,
  _timer: null,

  // The current search result.
  _result: null,
  // The listener to pass back results to.
  _listener: null,

  _parser: MailServices.headerParser,

  applicableHeaders: new Set(["addr_to", "addr_cc", "addr_bcc", "addr_reply"]),

  // Private methods

  _checkDuplicate(card, emailAddress) {
    var lcEmailAddress = emailAddress.toLocaleLowerCase();

    return this._result._searchResults.some(function(result) {
      return result.value.toLocaleLowerCase() == lcEmailAddress;
    });
  },

  _addToResult(card) {
    let mbox = this._parser.makeMailboxObject(
      card.displayName,
      card.isMailList
        ? card.getProperty("Notes", "") || card.displayName
        : card.primaryEmail
    );
    if (!mbox.email) {
      return;
    }

    let emailAddress = mbox.toString();

    // If it is a duplicate, then just return and don't add it. The
    // _checkDuplicate function deals with it all for us.
    if (this._checkDuplicate(card, emailAddress)) {
      return;
    }

    // Find out where to insert the card.
    var insertPosition = 0;

    // Next sort on full address
    while (
      insertPosition < this._result._searchResults.length &&
      emailAddress > this._result._searchResults[insertPosition].value
    ) {
      ++insertPosition;
    }

    this._result._searchResults.splice(insertPosition, 0, {
      value: emailAddress,
      card,
    });
  },

  // nsIObserver

  observe(subject, topic, data) {
    if (topic == "quit-application") {
      Services.obs.removeObserver(this, "quit-application");
    } else if (topic != "timer-callback") {
      return;
    }

    // Force the individual query items to null, so that the memory
    // gets collected straight away.
    this.stopSearch();
    this._book = null;
    this._context = -1;
    this._query = null;
    this._attributes = null;
  },

  // nsIAutoCompleteSearch

  startSearch(aSearchString, aParam, aPreviousResult, aListener) {
    let params = JSON.parse(aParam) || {};
    let applicable =
      !("type" in params) || this.applicableHeaders.has(params.type);

    this._result = new nsAbLDAPAutoCompleteResult(aSearchString);
    aSearchString = aSearchString.toLocaleLowerCase();

    // If the search string isn't value, or contains a comma, or the user
    // hasn't enabled autocomplete, then just return no matches / or the
    // result ignored.
    // The comma check is so that we don't autocomplete against the user
    // entering multiple addresses.
    if (!applicable || !aSearchString || aSearchString.includes(",")) {
      this._result.searchResult = ACR.RESULT_IGNORED;
      aListener.onSearchResult(this, this._result);
      return;
    }

    // The rules here: If the current identity has a directoryServer set, then
    // use that, otherwise, try the global preference instead.
    var acDirURI = null;
    var identity;

    if ("idKey" in params) {