(function (paw, utils) {
  function PawInputSelectpickerComponent($elt, settings) {
    var self = this;
    this.$elt = $elt;
    this.settings = settings;

    this.apiUrl = this.$elt.data("url");
    this.isApi = utils.value.isSet(this.apiUrl);

    this.picker = null;
    this.cachedItems = null;
    this.preselected = [];

    this.onShow = function () {
      if (self.isApi) {
        self.loadItems();
      }
    };

    this.onSelected = function () {
      var selected = [];
      self.$elt.find("> option:selected").each(function () {
        var $opt = $(this);
        selected.push(
          self.settings.selectionDisplayText ? $opt.text() : $opt.val()
        );
      });
      self.renderSelectedItems(selected);
    };
  }

  PawInputSelectpickerComponent.initSelectpicker = function ($elt, settings) {
    $elt.selectpicker(
      paw.lang.append(
        {
          selectedText: "",
        },
        settings || {}
      )
    );

    var picker = $elt.data("selectpicker");
    picker.$menu.addClass($elt.data("custom-class"));
    if (paw.utils.value.isSet(picker.$bsContainer)) {
      picker.$bsContainer.addClass("paw-select-container");
    }
    return picker;
  };

  PawInputSelectpickerComponent.prototype.init = function () {
    var self = this;
    var preselectedVals = this.$elt.attr("data-preselected-value");
    var value = this.$elt.val();
    console.log("Preselected vals?", preselectedVals);
    if (preselectedVals) {
      this.preselected = preselectedVals.split(",");
      if (this.preselected.length === 1 && this.preselected[0].length === 0) {
        this.preselected = [];
      }

      paw.utils.iterable.iterate(this.preselected, function (val) {
        self.$elt.append(
          '<option value="' + val + '" selected>' + val + "</option>"
        );
      });
    } else if (utils.value.isArray(value)) {
      console.warn("Array data preselection not supported yet!");
    } else if (utils.value.isSet(value)) {
      var $opt = this.$elt.find('option[value="' + value + '"]');
      $opt.attr("selected", true);
      this.preselected = [
        this.settings.selectionDisplayText ? $opt.text() : $opt.val(),
      ];
    }

    this.picker = PawInputSelectpickerComponent.initSelectpicker(
      this.$elt,
      this.settings
    );

    self.renderSelectedItems(this.preselected);

    this.$elt.on("show.bs.select", this.onShow);
    this.$elt.on("changed.bs.select", this.onSelected);
  };

  PawInputSelectpickerComponent.prototype.destroy = function () {
    this.$elt.off("show.bs.select", this.onShow);
    this.$elt.off("changed.bs.select", this.onSelected);
  };

  PawInputSelectpickerComponent.prototype.loadItems = function () {
    var self = this;
    if (paw.utils.value.isSet(this.cachedItems)) {
      return;
    }
    this.$elt.empty();

    return paw.utils.async.get(this.apiUrl).then(function (results) {
      self.cachedItems = results;
      paw.utils.iterable.iterate(results, function (result) {
        self.$elt.append(
          '<option value="' +
            result.Key +
            '"' +
            (self.preselected.indexOf(result.Key) > -1 ? " selected" : "") +
            ">" +
            paw.utils.value.strReplace(result.Value, "|", "-") +
            "</option>"
        );
      });
      self.$elt.selectpicker("refresh");
      self.renderSelectedItems(self.preselected);
    });
  };

  PawInputSelectpickerComponent.prototype.renderSelectedItems = function (
    selected
  ) {
    this.picker.$button
      .find(".filter-option-inner-inner")
      .html(selected.length === 0 ? "&nbsp;" : selected.join(", "));
  };

  paw.com.input.PawInputSelectpickerComponent = PawInputSelectpickerComponent;
})(paw, paw.utils);
