import $ from "jquery";

export function createSelect2Config(endpoint, placeholder) {
  return {
    placeholder: placeholder,
    minimumInputLength: 0,
    minimumResultsForSearch: 0,
    cache: true,
    allowClear: true,
    escapeMarkup: function (markup) {
      return markup;
    },
    ajax: {
      url: endpoint,
      dataType: "json",
      delay: 250,
      data: function (params) {
        return {
          search: params.term || "",
          page: params.page || 1,
        };
      },
      processResults: function (data, params) {
        params.page = params.page || 1;

        return {
          results: data.results.map(function (item) {
            return {
              id: item.id,
              text: item.name,
            };
          }),
          pagination: {
            more: data.pagination.more,
          },
        };
      },
    },
    templateSelection: function (selection) {
      if (selection.id === "") {
        return selection.text;
      }
      return selection.text;
    },
  };
}
