/**
 *
 * @param {DOM} domItem
 * @param {String} url
 * @param {String} placeholder
 */
let ClassSelect = function (domItem, url, placeholder, allowClear = false, params = {}, dropdownParent = "", hideSearch = false) {
  this.url = url;
  this.item = domItem;
  this.params = params;
  this.dropdownParent = dropdownParent;
  this.hideSearch = hideSearch;

  this.config = {
    placeholder: placeholder,
    allowClear: allowClear,
    dropdownParent: dropdownParent != "" ? dropdownParent : domItem.parent(),
    language: "es",
    ajax: {
      url: () => {
        return this.url;
      },
      data: (params) => {
        let q = $.trim(params.term);
        let d = {
          q: q,
          page: params.page || 1,
        };

        for (let key in this.params) {
          d[key] = this.params[key];
        }

        return d;
      },
      processResults: function (data) {
        return {
          results: $.map(data, function (obj) {
            return {
              id: obj.id,
              text: obj.nombre ?? obj.name,
              desc: obj.description,
            };
          }),
        };
      },
      cache: true,
    },
  };
  this.init = function () {
    if (this.item.length) {

      if (this.hideSearch) {
        this.config.minimumResultsForSearch = -1;
      }

      this.item = this.item.select2(this.config);
      // $.fn.modal.Constructor.prototype.enforceFocus = function () {};
    }
  };
  this.setOption = function (id, nombre) {
    var newOption = new Option(nombre, id, false, false);
    this.item.append(newOption);
    this.item.val(id).trigger("change");
  };
  this.reset = function () {
    this.item.val(null).trigger("change");
  };
  this.setParams = function (params) {
    this.params = params;
  };
  this.getVal = function () {
    return this.item.val();
  };
  this.setVal = function (val) {
    return this.item.val(val).trigger("change");
  };
  this.empty = function () {
    return this.item.empty().trigger("change");
  };
  this.readOnly = function () {
    this.item.enable(false);
  };
  this.enable = () => {
    this.item.enable(true);
  };
  this.fixWithScroll = function () { };
  this.getText = () => {
    return this.item.find(":selected").text();
  };
  this.onChange = function (callback) {
    this.item.on('change', callback);
  };
  this.offChange = function () {
    this.item.off('change');
  };

};

export default ClassSelect;
