'use strict';

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

const index = require('./index-7cdf1df1.js');
require('./index-c2a077ae.js');
const dataModel = require('./data-model-f9df493f.js');
require('./BaseField-f50bb8f0.js');
require('./FieldModelGenerator-5a321a60.js');
require('./date-8e8ca89a.js');
require('./index-e79eb186.js');
const tableConfig = require('./table-config-b20b4da1.js');
require('./string-9e6ebf63.js');
require('./membership-config-47f4733e.js');
require('./User-ed078a17.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-13fb62eb.js');
require('./kimlikApi-6a581864.js');
require('./data-transfer-field-025bce2f.js');
require('./filter-52876f3c.js');
require('./cookie-8a49bf23.js');
const viewConfig = require('./view-config-f8b4b929.js');
require('./attachment-c2bc9126.js');
const instance = require('./instance-adc7fc02.js');
const session = require('./session-a266bfc2.js');
const detailViewConfig = require('./detail-view-config-b47f4106.js');
require('./index-35a4d634.js');
const commonWrapperUtil = require('./common-wrapper-util-89cc9c36.js');
require('./pair-config-3ff31ab1.js');
const pairConfig = require('./pair-config-5bbf234b.js');

class AtamaMemberPairsOverviewViewConfig extends viewConfig.DvnAppViewConfig {
  static decode(json) {
    const model = Object.assign(Object.create(AtamaMemberPairsOverviewViewConfig.prototype), json);
    model.table = tableConfig.TableConfig.decode(model.table);
    return model;
  }
}

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) {
  if (!config) {
    return null;
  }
  const i18n = language === 'tr' ? tr : en;
  const { role } = mentornityCookieContext;
  const viewingGroups = role === 'mentor' && config.menteeType === 'group';
  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.getFieldsToShow(role, config);
  const 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 => !['fullName', 'imageUrl', 'imagePlaceholderValue'].includes(field.fieldId));
  return 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' : 'fullName',
            },
          },
          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.getFieldsToShow(role, config);
  const detailViewMembershipFields = tableConfig.decodeFields([...commonWrapperUtil.commonUserInfoFields, ...fields]);
  const detailViewCardFields = [...defaultUserFields, ...commonWrapperUtil.convertFieldsToFieldReferences(fields)]
    .filter(field => !['fullName', '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: 'fullName',
          },
          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;
    }
  }
  componentWillLoad() {
    const { context, headers } = session.getSessionDetails();
    this.mentornityBridgeApi = new commonWrapperUtil.MentornityBridgeApi(session.mentornityApiEndpoint, context, headers);
    instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers)
      .getOrganisationConfig(context.organisationId)
      .then((response) => {
      this.organisationConfig = instance.Config.decode(response);
    });
  }
  render() {
    const { context } = session.getSessionDetails();
    const { language, mentornityBridgeApi, organisationConfig, viewUserDetailDialogActionData } = this;
    const pairOverviewViewConfig = getPairOverviewViewConfig(context, language, organisationConfig);
    if (!pairOverviewViewConfig) {
      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: pairOverviewViewConfig }), viewUserDetailDialogActionData &&
      index.h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.viewUserDetailDialogActionData = undefined }, index.h("dvn-app-view-detail-view", { apiData: mentornityBridgeApi, id: "user-page", params: getUserDetailDialogParams(viewUserDetailDialogActionData), view: getUserDetailDialogViewConfig(context, organisationConfig) }))));
  }
};

exports.mentornity_pairs_overview_wrapper = MentornityPairsOverviewWrapper;
