'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index$2 = require('./index-7cdf1df1.js');
const index = require('./index-c2a077ae.js');
const dataModel = require('./data-model-f9df493f.js');
require('./BaseField-f50bb8f0.js');
const FieldModelGenerator = require('./FieldModelGenerator-5a321a60.js');
require('./date-8e8ca89a.js');
const index$1 = require('./index-e79eb186.js');
require('./table-config-b20b4da1.js');
const User = require('./User-ed078a17.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-d48a0164.js');
const calendar = require('./calendar-9f82f772.js');
const listFetchState = require('./list-fetch-state-4917b40d.js');
const pairConfig = require('./pair-config-3ff31ab1.js');
const ui = require('./ui-63800053.js');
const pairRequest = require('./pair-request-21d16db8.js');
const field = require('./field-161bf2df.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$1 = field.findField(fields, fieldId);
      if (!field$1) {
        console.error(`Field with id ${fieldId} not found. Available fields are ${fields.map(f => f.id).join(', ')}`);
      }
      const value = dataModel.getDataModelFieldDisplayValue(item, field$1);
      if (field$1.type === index.TextField.type && containsText(value, textFilter)) {
        return true;
      }
      else if (field$1.type === FieldModelGenerator.MultipleChoiceField.type) {
        const matchesAnyOption = (value || []).some(optionValue => (containsText(field$1.getOptionOfValue(optionValue).label, textFilter)));
        if (matchesAnyOption) {
          return true;
        }
      }
      else if (field$1.type === index$1.SingleChoiceField.type) {
        const matchesAnyOption = containsText(field$1.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) {
    index$2.registerInstance(this, hostRef);
    this.isSendingRequest = false;
    this.list = listFetchState.ListFetchState.init();
    this.sentRequestList = listFetchState.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;
    }
  }
  componentDidLoad() {
    this.fetchMembershipConfigOfMemberToShow();
    this.fetchSentRequestList();
    this.fetchSelectionList();
    this.uiHelper = new ui.ResponsiveUIHelper(this.el, this.onSizeChange);
  }
  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$1 = pairConfig.PairConfig.decode(table.toObject());
    const selectionConfig = pairConfig.getPairConfigSelectionConfigForRole(pairConfig$1, 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.fetchSelectionList();
        this.fetchSentRequestList();
        this.componentDidLoad();
        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 (index$2.h("div", { class: "d-flex justify-content-center pt-3" }, index$2.h("dvn-progress", { indefinite: true })));
    }
    const pairConfig$1 = pairConfig.PairConfig.decode(view.table);
    const selectionConfig = pairConfig.getPairConfigSelectionConfigForRole(pairConfig$1, 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 < ui.ResponsiveSize.Medium;
    const showHeaders = !showMobileUI;
    const showSelectionList = shownTab === 'list-to-select' || !showMobileUI;
    const showPairRequests = shownTab === 'pair-requests' || !showMobileUI;
    return (index$2.h(index$2.Host, { class: "row" }, showMobileUI &&
      index$2.h("div", { class: "col-sm-12 d-flex justify-content-center mt-3" }, index$2.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 &&
      index$2.h("div", { class: {
          ['col-sm-12 col-md-8 pt-3']: !showMobileUI,
          ['col-sm-12 pt-2']: showMobileUI,
        } }, index$2.h("div", { class: "ml-2 mb-2 d-flex align-items-center" }, showHeaders && index$2.h("small", null, index$2.h("b", null, ((_a = i18n.listToSelect) === null || _a === void 0 ? void 0 : _a.toLocaleUpperCase()) || 'LIST TO SELECT'), "\u00A0"), (list.isPending && list.data) &&
        index$2.h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })), (list.isPending && !list.data) &&
        index$2.h("div", { class: "d-flex justify-content-center" }, index$2.h("dvn-progress", { indefinite: true })), list.data &&
        index$2.h("div", null, index$2.h("div", { class: "mb-3" }, index$2.h("dvn-input", { leaned: true, onChange: (e) => this.textFilter = e.detail, placeholder: i18n.searchPlaceholder || 'Search by any info', width: "100%" })), items.length > 0
          ? index$2.h("dvn-card-list-view", { config: cardUIConfig, fields: membershipConfigToShow.fields, items: items })
          : index$2.h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, textFilter ? i18n.noItemMatchesFilter : i18n.noItemToSelect))), showPairRequests &&
      index$2.h("div", { class: {
          ['col-sm-12 col-md-4 pt-3']: !showMobileUI,
          ['col-sm-12 pt-2']: showMobileUI,
        } }, index$2.h("div", { class: "ml-2 mb-2 d-flex align-items-center" }, showHeaders && index$2.h("small", null, index$2.h("b", null, ((_b = i18n.sentRequests) === null || _b === void 0 ? void 0 : _b.toLocaleUpperCase()) || 'SENT REQUESTS'), "\u00A0"), (sentRequestList.isPending && sentRequestList.data) &&
        index$2.h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })), index$2.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) &&
        index$2.h("div", { class: "d-flex justify-content-center mt-3" }, index$2.h("dvn-progress", { indefinite: true })), sentRequestList.data &&
        index$2.h("div", null, sentRequestList.data.length > 0
          ? sentRequestList.data
            .sort((a, b) => b.requestedAt - a.requestedAt)
            .map((request) => (index$2.h("dvn-card", { key: request._id, elevation: 0, leaned: true, bodyLeaned: true, style: { margin: '1rem 0 0 0' } }, index$2.h("div", { class: "d-flex justify-content-between align-items-center pr-2" }, index$2.h("dvn-info-summary", { title: User.getUserFullName(dataModel.getDataModelField(request, 'sentTo')), subTitle: calendar.CalendarUtils.format(new Date(request.requestedAt * 1000), i18n.sentOnDateFormat || 'DD MMM YYYY, HH:mm') }, index$2.h("dvn-image", { slot: "media", src: dataModel.getDataModelField(request, 'sentTo').imageUrl, shape: "circle" })), index$2.h("dvn-button", { leaned: true, scale: "small", shape: "rounded", tagMode: true, tint: pairRequest.getTintForStatus(request), view: "ghost" }, pairRequest.getLabelForStatus(i18n.statusLabels, request))))))
          : index$2.h("div", { class: "mt-3" }, index$2.h("dvn-card", { elevation: 0, leaned: true, tint: "neutral" }, i18n.noSentRequests)))), this.selectedUser &&
      index$2.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.'), index$2.h("div", { slot: "actions" }, index$2.h("dvn-button", { disabled: this.isSendingRequest, onClick: () => this.selectedUser = undefined, tint: "danger", view: "flat" }, i18n.cancel || 'Cancel'), index$2.h("dvn-button", { disabled: this.isSendingRequest, progressing: this.isSendingRequest, onClick: () => this.onConfirm(), tint: "secondary", view: "flat" }, i18n.yes || 'Yes')))));
  }
  get el() { return index$2.getElement(this); }
};

exports.dvn_app_view_atama_member_pair_selection_view = DvnAppViewAtamaMemberPairSelectionView;
