import { r as registerInstance, h, H as Host, g as getElement } from './index-ecdfb761.js';
import { a as ResponsiveUIHelper, R as ResponsiveSize } from './ui-0156b0ee.js';
import { a as getDataModelFieldDisplayValue, g as getDataModelField } from './data-model-88af49fc.js';
import { L as ListFetchState } from './list-fetch-state-e772aa74.js';
import { P as PairConfig, b as getPairConfigSelectionConfigForRole } from './pair-config-13b5a7c1.js';
import { C as CalendarUtils } from './calendar-470c802a.js';
import { g as getTintForStatus, a as getLabelForStatus } from './pair-request-ee2b9bbc.js';
import { M as MultipleChoiceField } from './index-4e451db4.js';
import { S as SingleChoiceField } from './index-23baeeef.js';
import { T as TextField } from './index-150b6a59.js';
import { f as findField } from './field-5a687ea4.js';
import './table-config-d73a72ab.js';
import './FieldModelGenerator-378c8613.js';
import './reference-field-a5b414d1.js';
import './BaseField-0b01dc2c.js';
import './index-61dcd269.js';
import './FieldGenerator-3ae403b2.js';
import './date-1bc489bd.js';
import './index-09efdc01.js';
import './index-a3ca021c.js';
import './_commonjsHelpers-27f122dd.js';
import './moment-65eca6b3.js';

function generateActionConfig(i18n, selectionConfig) {
  var _a;
  const actions = [
    {
      ui: {
        label: i18n.seeDetails || 'See Details',
        name: 'view-details',
        view: 'flat',
        tint: 'neutral',
      }
    }
  ];
  if ((_a = selectionConfig === null || selectionConfig === void 0 ? void 0 : selectionConfig.selectionUI) === null || _a === void 0 ? void 0 : _a.showMessageButton) {
    actions.push({
      ui: {
        label: i18n.sendMessage || 'Message',
        name: 'send-message',
        view: 'flat',
        tint: 'neutral',
      }
    });
  }
  actions.push({
    data: {
      type: 'navigation',
      direction: 'forward',
      params: {
        conversionConfig: {
          'item._id': 'userId',
        }
      }
    },
    ui: {
      label: i18n.select || 'Select',
      name: 'select-pair',
      view: 'ghost',
    }
  });
  return actions;
}

function filterList(listConfig, fields, list, textFilter) {
  if (!list || !textFilter) {
    return list;
  }
  return list.filter(item => {
    return (listConfig.body.fields || []).some(bodyFieldConfig => {
      const { fieldId } = bodyFieldConfig;
      const field = findField(fields, fieldId);
      if (!field) {
        console.error(`Field with id ${fieldId} not found. Available fields are ${fields.map(f => f.id).join(', ')}`);
      }
      const value = getDataModelFieldDisplayValue(item, field);
      if (field.type === TextField.type && containsText(value, textFilter)) {
        return true;
      }
      else if (field.type === MultipleChoiceField.type) {
        const matchesAnyOption = (value || []).some(optionValue => (containsText(field.getOptionOfValue(optionValue).label, textFilter)));
        if (matchesAnyOption) {
          return true;
        }
      }
      else if (field.type === SingleChoiceField.type) {
        const matchesAnyOption = containsText(field.getOptionOfValue(value).label, textFilter);
        if (matchesAnyOption) {
          return true;
        }
      }
      return false;
    });
  });
}
function containsText(value, filter) {
  return new RegExp(filter, 'i').test(value);
}

function getDescriptionForError(error) {
  switch (error.message) {
    case 'same-subscription-exists':
      return 'You already sent request to this user.';
    case 'selection-limit-reached':
      return 'You reached the selection limit.';
    case 'subscription-limit-reached':
      return 'You reached your pair limit.';
    default:
      return 'Could not create pair.';
  }
}
const DvnAppViewAtamaMemberPairSelectionView = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.isSendingRequest = false;
    this.list = ListFetchState.init();
    this.sentRequestList = ListFetchState.init();
    this.textFilter = '';
    this.shownTab = 'list-to-select';
    this.onSizeChange = (size) => {
      this.size = size;
    };
  }
  onAction(event) {
    const action = event.detail;
    if (action.name === 'select-pair') {
      this.selectedUser = action.params.item;
    }
  }
  componentWillLoad() {
    this.uiHelper = new ResponsiveUIHelper(this.el, this.onSizeChange);
    this.fetchInitialData();
  }
  fetchInitialData() {
    this.fetchMembershipConfigOfMemberToShow();
    this.fetchSentRequestList();
    this.fetchSelectionList();
  }
  fetchMembershipConfigOfMemberToShow() {
    var _a;
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId } = this.params;
    const memberToShowTableName = (_a = table.fields.find(f => f.type === 'reference' && f.id === memberToViewRefFieldId)) === null || _a === void 0 ? void 0 : _a.otherCollection;
    this.apiUye.getMembershipConfigWithName(memberToShowTableName).then(response => {
      this.membershipConfigToShow = response;
    }, error => notifier.alert(i18n.fetchConfigurationError || 'Getting configuration failed.', error.status));
  }
  fetchSelectionList() {
    var _a;
    const { list } = this;
    if (list.isPending) {
      return;
    }
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId, userRefFieldValue } = this.params;
    const memberToShowTableName = (_a = table.fields.find(f => f.type === 'reference' && f.id === memberToViewRefFieldId)) === null || _a === void 0 ? void 0 : _a.otherCollection;
    this.list = list.beforeFetch();
    this.apiAtama.getSelectionList(table.base, memberToShowTableName, table._id, userRefFieldValue, memberToViewRefFieldId)
      .then(response => {
      this.list = list.afterFetch(response, false);
    }, error => {
      this.list = list.afterFetchError(error);
      notifier.alert(i18n.fetchSelectionListError || 'Getting selection list failed.', error.status);
    });
  }
  fetchSentRequestList() {
    const { sentRequestList } = this;
    if (sentRequestList.isPending) {
      return;
    }
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { userRefFieldValue } = this.params;
    this.sentRequestList = sentRequestList.beforeFetch();
    this.apiAtama.getSentRequests(table.base, `${table._id}-requests`, userRefFieldValue)
      .then(response => {
      this.sentRequestList = sentRequestList.afterFetch(response, false);
    }, error => {
      this.sentRequestList = sentRequestList.afterFetchError(error);
      notifier.alert(i18n.fetchSentRequestListError || 'Getting sent requests failed.', error.status);
    });
  }
  onConfirm() {
    const { params, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId, userRefFieldId, userRefFieldValue } = params;
    const pairConfig = PairConfig.decode(table.toObject());
    const selectionConfig = getPairConfigSelectionConfigForRole(pairConfig, userRefFieldId);
    if (selectionConfig.initiation === 'approvingly') {
      this.isSendingRequest = true;
      this.apiAtama.sendPairRequest(table.base, `${table._id}-requests`, userRefFieldId, userRefFieldValue, memberToViewRefFieldId, this.selectedUser).then(() => {
        this.isSendingRequest = false;
        this.selectedUser = undefined;
        this.fetchInitialData();
        this.notifier.congratulate(i18n.pairRequestIsSent || 'Request is sent');
      }).catch(e => {
        this.isSendingRequest = false;
        this.selectedUser = undefined;
        this.notifier.alert(getDescriptionForError(e.data));
      });
    }
  }
  render() {
    var _a, _b;
    const { list, membershipConfigToShow, params, sentRequestList, shownTab, size, textFilter, view } = this;
    const { userRefFieldId } = params;
    const { ui: { i18n } } = view;
    if (!membershipConfigToShow) {
      return (h("div", { class: "d-flex justify-content-center pt-3" }, h("dvn-progress", { indefinite: true })));
    }
    const pairConfig = PairConfig.decode(view.table);
    const selectionConfig = getPairConfigSelectionConfigForRole(pairConfig, userRefFieldId);
    const cardUIConfig = {
      main: {
        cardViewConfig: Object.assign(Object.assign({}, view.ui.main.cardViewConfig), { footer: {
            actions: generateActionConfig(i18n, selectionConfig),
          } })
      }
    };
    const items = filterList(cardUIConfig.main.cardViewConfig, membershipConfigToShow.fields, list.data, textFilter);
    const showMobileUI = size < ResponsiveSize.Medium;
    const showHeaders = !showMobileUI;
    const showSelectionList = shownTab === 'list-to-select' || !showMobileUI;
    const showPairRequests = shownTab === 'pair-requests' || !showMobileUI;
    return (h(Host, { class: "row" }, showMobileUI &&
      h("div", { class: "col-sm-12 d-flex justify-content-center mt-3" }, h("dvn-content-switcher", { options: [
          {
            label: i18n.listToSelect || 'List to Select',
            value: 'list-to-select',
          },
          {
            label: i18n.sentRequests || 'Sent Requests',
            value: 'pair-requests',
          },
        ], onChange: (event) => this.shownTab = event.detail, value: this.shownTab })), showSelectionList &&
      h("div", { class: {
          ['col-sm-12 col-md-8 pt-3']: !showMobileUI,
          ['col-sm-12 pt-2']: showMobileUI,
        } }, h("div", { class: "ml-2 mb-2 d-flex align-items-center" }, showHeaders && h("small", null, h("b", null, ((_a = i18n.listToSelect) === null || _a === void 0 ? void 0 : _a.toLocaleUpperCase()) || 'LIST TO SELECT'), "\u00A0"), (list.isPending && list.data) &&
        h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })), (list.isPending && !list.data) &&
        h("div", { class: "d-flex justify-content-center" }, h("dvn-progress", { indefinite: true })), list.data &&
        h("div", null, h("div", { class: "mb-3" }, h("dvn-input", { leaned: true, onChange: (e) => this.textFilter = e.detail, placeholder: i18n.searchPlaceholder || 'Search by any info', width: "100%" })), items.length > 0
          ? h("dvn-card-list-view", { config: cardUIConfig, fields: membershipConfigToShow.fields, items: items })
          : h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, textFilter ? i18n.noItemMatchesFilter : i18n.noItemToSelect))), showPairRequests &&
      h("div", { class: {
          ['col-sm-12 col-md-4 pt-3']: !showMobileUI,
          ['col-sm-12 pt-2']: showMobileUI,
        } }, h("div", { class: "ml-2 mb-2 d-flex align-items-center" }, showHeaders && h("small", null, h("b", null, ((_b = i18n.sentRequests) === null || _b === void 0 ? void 0 : _b.toLocaleUpperCase()) || 'SENT REQUESTS'), "\u00A0"), (sentRequestList.isPending && sentRequestList.data) &&
        h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })), h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, (i18n.maxLimitMessage || 'You can send max {selectionLimit} requests at a time.')
        .replace(/{selectionLimit}/g, `${selectionConfig.selectionLimit}`)), (sentRequestList.isPending && !sentRequestList.data) &&
        h("div", { class: "d-flex justify-content-center mt-3" }, h("dvn-progress", { indefinite: true })), sentRequestList.data &&
        h("div", null, sentRequestList.data.length > 0
          ? sentRequestList.data
            .sort((a, b) => b.requestedAt - a.requestedAt)
            .map((request) => (h("dvn-card", { key: request._id, elevation: 0, leaned: true, bodyLeaned: true, style: { margin: '1rem 0 0 0' } }, h("div", { class: "d-flex justify-content-between align-items-center pr-2" }, h("dvn-info-summary", { title: getDataModelField(request, 'sentTo').name, subTitle: CalendarUtils.format(new Date(request.requestedAt * 1000), i18n.sentOnDateFormat || 'DD MMM YYYY, HH:mm') }, h("dvn-image", { slot: "media", shape: "circle", src: getDataModelField(request, 'sentTo').imageUrl, text: getDataModelField(request, 'sentTo').initials })), h("dvn-button", { leaned: true, scale: "small", shape: "rounded", tagMode: true, tint: getTintForStatus(request), view: "ghost" }, getLabelForStatus(i18n.statusLabels, request))))))
          : h("div", { class: "mt-3" }, h("dvn-card", { elevation: 0, leaned: true, tint: "neutral" }, i18n.noSentRequests)))), this.selectedUser &&
      h("dvn-dialog", { title: i18n.selectionConfirmationDialogTitle || 'Are you sure to select this user?', shown: !!this.selectedUser, onDismiss: () => this.selectedUser = undefined }, selectionConfig.initiation === 'approvingly'
        ? (i18n.selectionConfirmationDialogMessageForApproval || 'The user will receive a notification and the process will start after the user approves the request. Requests can only be canceled by the program administration.')
        : (i18n.selectionConfirmationDialogMessage || 'The user will receive a notification and the process will start immediately. Pairs can only be canceled by the program administration.'), h("div", { slot: "actions" }, h("dvn-button", { disabled: this.isSendingRequest, onClick: () => this.selectedUser = undefined, tint: "danger", view: "flat" }, i18n.cancel || 'Cancel'), h("dvn-button", { disabled: this.isSendingRequest, progressing: this.isSendingRequest, onClick: () => this.onConfirm(), tint: "secondary", view: "flat" }, i18n.yes || 'Yes')))));
  }
  get el() { return getElement(this); }
};

export { DvnAppViewAtamaMemberPairSelectionView as dvn_app_view_atama_member_pair_selection_view };
