'use strict';

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

const index = require('./index-36b3af04.js');
const dataModel = require('./data-model-c51de090.js');
require('./kimlikApi-85c6d3ac.js');
require('./data-transfer-field-0ce05c1a.js');
require('./filter-d5040f65.js');
const instance = require('./instance-79d61640.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-22218ac9.js');
const session = require('./session-3b788cd7.js');
const tableConfig = require('./table-config-444a77e4.js');
const detailViewConfig = require('./detail-view-config-594cc3b7.js');
const atamaMemberPairsOverviewViewConfig = require('./atama-member-pairs-overview-view-config-b5cdd803.js');
const pairConfig = require('./pair-config-b32393a8.js');
const commonWrapperUtil = require('./common-wrapper-util-25ff9eca.js');
require('./BaseField-d019ade6.js');
require('./FieldModelGenerator-205dd99c.js');
require('./index-74a00556.js');
require('./index-a8f1783c.js');
require('./date-25b104f6.js');
require('./index-fe19a98b.js');
require('./index-ae305bae.js');
require('./index-d90390f1.js');
require('./attachment-3090e25e.js');
require('./membership-dfbf512e.js');
require('./membership-config-707b2c51.js');
require('./string-de672b69.js');
require('./User-286a0714.js');
require('./CalendarConfig-9459e520.js');
require('./UserSettings-016122e8.js');
require('./cookie-370bc992.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./view-config-ec5f62df.js');
require('./pair-config-c9ce6f9a.js');

const en = {
  view: {
    accept: 'Accept',
    fetchConfigurationError: 'Getting configuration failed.',
    fetchListError: 'Fetching list failed.',
    noPairsMessage: 'You don\'t have any pairs.',
    noReceivedRequests: 'There are no pending requests.',
    pairs: 'Pairs',
    receivedRequests: 'Received Requests',
    reject: 'Reject',
    selectionCardActionTint: 'secondary',
    selectionCardActionLabel: 'Go to selection page',
    selectionCardMessage: 'You can view all available users and send them requests.',
    selectionCardTint: 'primary',
    selectionCardTitle: 'Selection is on!',
    sentOnDateFormat: 'DD MMM YYYY, HH:mm',
    statusLabels: {
      accepted: 'Accepted',
      canceled: 'Canceled',
      completed: 'Completed',
      rejected: 'Rejected',
      requested: 'Requested',
    },
    viewAndMeet: 'View & Meet',
  },
};
const tr = {
  view: {
    accept: 'Kabul Et',
    fetchConfigurationError: 'Ayarlar alınırken hata oluştu.',
    fetchListError: 'Seçim listesi alınırken hata oluştu.',
    noPairsMessage: 'Eşleştiğiniz kimse yok.',
    noReceivedRequests: 'Onay bekleyen istek yok.',
    pairs: 'Eşleşmeler',
    receivedRequests: 'Alınan İstekler',
    reject: 'Reddet',
    selectionCardActionTint: 'secondary',
    selectionCardActionLabel: 'Seçim sayfasına git',
    selectionCardMessage: 'Müsait olan tüm kullanıcıları görüp onlara istek gönderebilirsiniz.',
    selectionCardTint: 'primary',
    selectionCardTitle: 'Seçim başladı!',
    sentOnDateFormat: 'DD MMM YYYY, HH:mm',
    statusLabels: {
      accepted: 'Onaylandı',
      canceled: 'Reddedildi',
      completed: 'Sonlandırıldı',
      rejected: 'Reddedildi',
      requested: 'Gönderildi',
    },
    viewAndMeet: 'Detay & Toplantılar',
  },
};

function getPairOverviewParameters(mentornityCookieContext) {
  const { role } = mentornityCookieContext;
  // if user is mentor, then the view config should say that the 'subscribed' is viewing the 'subscriber'
  // if user is mentee, then it should say otherwise
  const userRefFieldIdValue = role === 'mentor' ? 'subscribed' : 'subscriber';
  const memberToViewRefFieldIdValue = role === 'mentor' ? 'subscriber' : 'subscribed';
  return {
    memberToViewRefFieldId: memberToViewRefFieldIdValue,
    userRefFieldId: userRefFieldIdValue,
    viewIdToNavigateToSelectPair: 'pair-selection-page',
    viewIdToViewRequestSender: 'user-page',
  };
}
function getPairOverviewViewConfig(mentornityCookieContext, language, config, viewConfigs) {
  const i18n = language === 'tr' ? tr : en;
  const { role } = mentornityCookieContext;
  const viewingGroups = role === 'mentor' && config.menteeType === 'group';
  let cardBodyFields = [];
  const viewName = role === 'mentor'
    ? instance.MentornityViewConfigViewName.MenteePairList
    : instance.MentornityViewConfigViewName.MentorPairList;
  const viewConfig = commonWrapperUtil.getViewConfigForViewName(viewConfigs, viewName);
  if (viewConfig) {
    const pairOverviewConfig = viewConfig.dvnAppViewConfig;
    cardBodyFields = pairOverviewConfig.ui.main.cardViewConfig.body.fields;
  }
  else {
    const profileFieldVisibility = role === 'mentor' ? config.profileFieldVisibilities.mentee : config.profileFieldVisibilities.mentor;
    const defaultUserFields = ['title', 'bio', 'skills', 'imagePlaceholderValue'].filter(id => profileFieldVisibility[id]).map(id => ({ fieldId: id }));
    const defaultGroupFields = ['description', 'imagePlaceholderValue'].map(id => ({ fieldId: id }));
    const fields = viewingGroups ? [] : commonWrapperUtil.getAvailableMetadataFields(role, config);
    cardBodyFields = (viewingGroups ? defaultGroupFields : [...defaultUserFields, ...commonWrapperUtil.convertFieldsToFieldReferences(fields)])
      .slice(0, 3)
      .map(fieldConfig => (Object.assign(Object.assign({}, fieldConfig), { lines: 1 }))) // to trim long texts
      .filter(field => !['name', 'imageUrl', 'imagePlaceholderValue'].includes(field.fieldId));
  }
  return atamaMemberPairsOverviewViewConfig.AtamaMemberPairsOverviewViewConfig.decode({
    _id: 'pair-overview-page',
    ui: {
      i18n: i18n.view,
      main: {
        cardViewConfig: {
          header: {
            cover: {
              size: 100,
            },
            image: {
              fieldId: 'imageUrl',
              placeholderFieldId: 'imagePlaceholderValue',
              shape: viewingGroups ? 'rounded' : undefined,
              size: 72,
            },
            title: {
              fieldId: viewingGroups ? 'title' : 'name',
            },
          },
          body: {
            fields: cardBodyFields,
          },
          footer: {
            actions: [
              {
                data: {
                  type: 'navigation',
                  direction: 'forward',
                  placement: 'view',
                  viewId: 'subscriptions',
                  params: {
                    conversionConfig: {
                      'item._id': 'memberToViewRefFieldValue',
                      'item.subscription._id': 'pairId',
                    }
                  }
                },
                ui: {
                  label: i18n.view.viewAndMeet || 'View & Meet',
                  name: 'open-pair-detail-view',
                  view: 'ghost',
                }
              }
            ]
          }
        },
      },
    },
    params: {},
    table: pairConfig.pairConfig(config, undefined, commonWrapperUtil.getPairConfigOptionsFromOrganisationConfig(config)),
  });
}
function getUserDetailDialogParams(actionData) {
  return {
    itemId: actionData.params.item._id,
  };
}
function getUserDetailDialogViewConfig(mentornityCookieContext, config) {
  if (!config) {
    return undefined;
  }
  const { organisationId, role } = mentornityCookieContext;
  const profileFieldVisibility = role === 'mentor' ? config.profileFieldVisibilities.mentee : config.profileFieldVisibilities.mentor;
  const defaultUserFields = ['title', 'bio', 'skills'].filter(id => profileFieldVisibility[id]).map(id => ({ fieldId: id }));
  const fields = commonWrapperUtil.getAvailableMetadataFields(role, config);
  const detailViewMembershipFields = tableConfig.decodeFields([...mentorintyBridgeApi.commonUserInfoFields, ...fields]);
  const detailViewCardFields = [...defaultUserFields, ...commonWrapperUtil.convertFieldsToFieldReferences(fields)]
    .filter(field => !['name', 'imageUrl'].includes(field.fieldId));
  const showMessageButton = [
    instance.InfoVisibility.allMentees,
    instance.InfoVisibility.everyone,
  ].includes(config.conversationPermissions.mentor);
  return detailViewConfig.DetailViewConfig.decode({
    table: tableConfig.TableConfig.decode({
      base: organisationId,
      name: 'mentees',
    }),
    ui: {
      fields: detailViewMembershipFields,
      cardConfig: {
        header: {
          title: {
            fieldId: 'name',
          },
          actions: showMessageButton ? [
            {
              ui: {
                label: 'Send Message',
                name: 'send-message',
              }
            }
          ] : [],
        },
        body: {
          fields: detailViewCardFields,
        }
      }
    },
  });
}

const MentornityPairsOverviewWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
  }
  onAction(event) {
    const action = event.detail;
    if (action.type === 'navigation') {
      const navigateAction = action;
      if (navigateAction.direction === 'forward') {
        const navigateForwardAction = action;
        if (navigateForwardAction.name === 'open-pair-detail-view') {
          const { memberToViewRefFieldValue, pairId } = navigateForwardAction.params;
          // called when mentor/mentee clicks the "View User & Meet" button on the user card
          window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-pair-detail', {
            detail: {
              userId: memberToViewRefFieldValue,
              pairId,
            }
          }));
        }
        if (navigateForwardAction.viewId === 'pair-selection-page') {
          // called when mentee clicks the "Go to mentor selection page" on the top announcement card
          window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-pair-selection-page', {}));
        }
        if (navigateForwardAction.viewId === 'user-page') {
          // called when mentor clicks the user information from the received requests list
          this.viewUserDetailDialogActionData = navigateForwardAction;
        }
      }
    }
    if (action.name === 'send-message') {
      // called when mentor clicks the "Send Message" button from the user detail dialog
      window.dispatchEvent(new CustomEvent('dvn.atama-pairs.send-message', {
        detail: {
          user: action.params.item.user,
        }
      }));
      this.viewUserDetailDialogActionData = undefined;
    }
  }
  async componentWillLoad() {
    const { language } = this;
    const { context, headers } = session.getSessionDetails();
    this.mentornityBridgeApi = new mentorintyBridgeApi.MentornityBridgeApi(session.mentornityApiEndpoint, context, headers);
    const mentornityApi = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    const getViewConfigsResponse = await mentornityApi.getViewConfigs(context.organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    const viewConfigs = getViewConfigsResponse.results;
    const config = await mentornityApi.getOrganisationConfig(context.organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = instance.Config.decode(config);
    this.atamaMemberPairsOverviewViewConfig = getPairOverviewViewConfig(context, language, this.organisationConfig, viewConfigs);
  }
  render() {
    const { context } = session.getSessionDetails();
    const { mentornityBridgeApi, organisationConfig, viewUserDetailDialogActionData } = this;
    if (!this.atamaMemberPairsOverviewViewConfig) {
      return null;
    }
    return (index.h("mentornity-root-wrapper", null, index.h("dvn-app-view-atama-member-pairs-overview-view", { apiAtama: mentornityBridgeApi, apiUye: mentornityBridgeApi, membership: dataModel.DataModel.decode({}), params: getPairOverviewParameters(context), view: this.atamaMemberPairsOverviewViewConfig }), viewUserDetailDialogActionData &&
      index.h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.viewUserDetailDialogActionData = undefined }, index.h("dvn-app-view-detail-view-card", { apiData: mentornityBridgeApi, id: "user-page", params: getUserDetailDialogParams(viewUserDetailDialogActionData), view: getUserDetailDialogViewConfig(context, organisationConfig) }))));
  }
};

exports.mentornity_pairs_overview_wrapper = MentornityPairsOverviewWrapper;
