'use strict';

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

const index = require('./index-1141a245.js');
const calendar = require('./calendar-e4b7baeb.js');
const User = require('./User-dbfbd45e.js');
const index$1 = require('./index-a2e99c85.js');
require('./apiBase-6c66ff1b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const session = require('./session-f588baa3.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-b1eaa56d.js');
const sozlukEntries = require('./sozluk-entries-3b9686e7.js');
const atamaMemberPairDetailViewConfig = require('./atama-member-pair-detail-view-config-7afc2686.js');
const pairConfig = require('./pair-config-2fe452ee.js');
const commonWrapperUtil = require('./common-wrapper-util-95591ac2.js');
require('./index-b776fc14.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-7a3433f2.js');
require('./data-model-01c368bc.js');
require('./BaseField-381327a9.js');
require('./membership-e87e02ed.js');
require('./table-config-969d3038.js');
require('./FieldModelGenerator-d61f01d4.js');
require('./reference-field-1239b0c3.js');
require('./index-2eea69a0.js');
require('./FieldGenerator-279a646b.js');
require('./date-a24d7714.js');
require('./index-0783d14f.js');
require('./index-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./index-61f9621a.js');
require('./string-de672b69.js');
require('./UserSettings-2a2399b1.js');
require('./cookie-e64bc800.js');
require('./kimlik-api-663f4884.js');
require('./index-33e96540.js');
require('./index-b7855ed6.js');
require('./attachment-a0cdf203.js');
require('./CalendarConfig-998f742e.js');
require('./i18n-0bcf144d.js');
require('./i18n-77d45414.js');
require('./pair-config-589dabd2.js');
require('./view-config-52c16db0.js');

const en = {
  detailView: {
    cancel: 'Cancel',
    createMeeting: 'Schedule Session',
    notScheduled: 'Not scheduled',
    dateFormatDay: 'DD MMM',
    dateFormatTime: 'HH:mm',
    endPair: 'Finish This Process',
    endPairConfirmationDescription: 'This action removes the pair from your account. You will not be able to schedule meetings with this person.',
    endPairConfirmationFinishPair: 'Finish the Process',
    endPairConfirmationTitle: 'Are you sure to end the process?',
    fetchConfigurationError: 'Getting configuration failed.',
    fetchItemError: 'Getting item failed.',
    info: 'INFO',
    meetings: 'MEETINGS',
    getMeeting: 'SELECT A DAY AND TIME',
    roleName: '',
    seeMore: 'See More',
    sendMessage: 'Send Message',
    viewDetails: 'View Details',
    goToSessionPage: 'Go to Session Page',
    completed: 'completed',
    meetingScheduled: 'meeting scheduled',
    meetingsScheduled: 'meetings scheduled',
    notScheduledYet: 'Not Scheduled Yet',
    aboutThisSession: 'About this session',
    session: 'SESSION'
  },
};
const pt_br = {
  detailView: {
    cancel: 'Cancelar',
    createMeeting: 'Agendar sessão',
    notScheduled: 'Não agendado',
    dateFormatDay: 'DD MMM',
    dateFormatTime: 'HH:mm',
    endPair: 'Concluir este processo',
    endPairConfirmationDescription: 'Esta ação remove o par de sua conta. Você não poderá agendar reuniões com esta pessoa.',
    endPairConfirmationFinishPair: 'Finalize o processo',
    endPairConfirmationTitle: 'Tem certeza de encerrar o processo?',
    fetchConfigurationError: 'Falha ao obter configuração.',
    fetchItemError: 'Falha ao obter item.',
    info: 'INFORMAÇÕES',
    meetings: 'ENCONTROS',
    getMeeting: 'SELECIONE UM DIA E HORÁRIO',
    roleName: '',
    seeMore: 'Ver mais',
    sendMessage: 'Enviar mensagem',
    viewDetails: 'Ver detalhes',
    goToSessionPage: 'Ir para a página da sessão',
    completed: 'concluído',
    meetingScheduled: 'reunião agendada',
    meetingsScheduled: 'reuniões agendadas',
    notScheduledYet: 'Ainda não agendado',
    aboutThisSession: 'Sobre esta sessão',
    session: 'Sessão'
  },
};
const tr = {
  detailView: {
    cancel: 'Vazgeç',
    createMeeting: 'Toplantı Oluştur',
    notScheduled: 'Toplantı düzenlenmedi',
    dateFormatDay: 'DD MMM',
    dateFormatTime: 'HH:mm',
    endPair: 'Eşleşmeyi Sonlandır',
    endPairConfirmationDescription: 'Eşleşmeyi bitirdiğinizde bu kişi sizin listenizden silinecek ve bu kişi ile artık toplantı oluşturamayacaksınız.',
    endPairConfirmationFinishPair: 'Eşleşmeyi Sonlandır',
    endPairConfirmationTitle: 'Eşleşmeyi sonlandırmak istediğinize emin misiniz?',
    fetchConfigurationError: 'Ayarlar alınırken hata oluştu.',
    fetchItemError: 'Detaylar alınırken hata oluştu.',
    info: 'BİLGİ',
    meetings: 'TOPLANTILAR',
    getMeeting: 'TOPLANTI OLUŞTUR',
    roleName: '',
    seeMore: 'Daha Fazla Bilgi',
    sendMessage: 'Mesaj Gönder',
    viewDetails: 'Detayları Gör',
    goToSessionPage: 'Toplantı sayfasına git',
    completed: 'tamamlandı',
    meetingScheduled: 'toplantı planlandı',
    meetingsScheduled: 'toplantı planlandı',
    notScheduledYet: 'Henüz Planlanmadı',
    aboutThisSession: 'Bu oturum hakkında',
    session: 'OTURUM'
  },
};

function getPairDetailParameters(mentornityCookieContext, config) {
  const { role } = mentornityCookieContext;
  const viewingGroups = role === 'mentor' && config.menteeType === 'group';
  // 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';
  const routeParams = session.getRouteParams(location.pathname);
  // don't show the message button if mentor is viewing group
  const showSendMessageButton = !viewingGroups;
  return {
    memberToViewRefFieldId: memberToViewRefFieldIdValue,
    userRefFieldId: userRefFieldIdValue,
    memberToViewRefFieldValue: new URLSearchParams(window.location.search).get('uid'),
    pairId: routeParams.id,
    viewIdToNavigateOnEndPair: 'pair-overview-page',
    showSendMessageButton,
  };
}
function getPairDetailViewConfig(mentornityCookieContext, language, config, goalConfig, viewConfigs) {
  const { role } = mentornityCookieContext;
  const viewName = role === 'mentor'
    ? session.MentornityViewConfigViewName.MenteePairDetail
    : session.MentornityViewConfigViewName.MentorPairDetail;
  const viewedUserRole = role === 'mentor' ? 'mentee' : 'mentor';
  const viewConfig = commonWrapperUtil.getViewConfigForViewName(viewConfigs, viewName);
  // set English default language
  let i18n = en;
  switch (language) {
    case 'tr':
      i18n = tr;
      break;
    case 'pt-br':
      i18n = pt_br;
  }
  const viewingGroups = role === 'mentor' && config.menteeType === 'group';
  // 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';
  let infoSummaryCardFields = [];
  let infoDetailCardFields = [];
  if (viewConfig) {
    const pairOverviewConfig = viewConfig.dvnAppViewConfig;
    infoSummaryCardFields = commonWrapperUtil.filterUnavailableMetadataFields(role, config, pairOverviewConfig.ui.main.infoSummaryCardViewConfig.body.fields);
    infoDetailCardFields = commonWrapperUtil.filterUnavailableMetadataFields(role, config, pairOverviewConfig.ui.main.infoDetailCardViewConfig.body.fields);
  }
  else {
    const profileFieldVisibility = role === 'mentor' ? config.profileFieldVisibilities.mentee : config.profileFieldVisibilities.mentor;
    const defaultUserFields = ['title', 'bio', 'skills'].filter(id => profileFieldVisibility[id]).map(id => ({ fieldId: id }));
    const defaultGroupFields = ['description', 'members'].map(id => ({ fieldId: id, showTitle: true }));
    const fields = viewingGroups ? [] : commonWrapperUtil.getAvailableMetadataFields(role, viewedUserRole, config);
    infoDetailCardFields = (viewingGroups ? defaultGroupFields : [...defaultUserFields, ...commonWrapperUtil.convertFieldsToFieldReferences(fields)])
      .filter(field => !['name', 'imageUrl'].includes(field.fieldId));
    infoSummaryCardFields = infoDetailCardFields
      .slice(0, 3)
      .map(fieldConfig => (Object.assign(Object.assign({}, fieldConfig), { lines: 1 }))); // to trim long texts
  }
  return atamaMemberPairDetailViewConfig.AtamaMemberPairDetailViewConfig.decode({
    _id: 'pair-detail-page',
    i18nEntryId: 'pair-detail-page',
    ui: {
      i18n: Object.assign(Object.assign({}, i18n.detailView), { roleName: getLocalisedRoleName(config, role, language, viewingGroups) }),
      main: {
        infoSummaryCardViewConfig: {
          header: {},
          body: {
            fields: infoSummaryCardFields,
          },
          footer: {}
        },
        infoDetailCardViewConfig: {
          header: {},
          body: {
            fields: infoDetailCardFields,
          },
          footer: {}
        },
      },
    },
    space: {},
    title: 'Pair Details',
    type: 'atama-member-pair-detail-view',
    table: pairConfig.pairConfig(config, goalConfig, commonWrapperUtil.getPairConfigOptionsFromOrganisationConfig(config)),
    params: {
      userRefFieldId: {
        required: true,
        value: userRefFieldIdValue
      },
      memberToViewRefFieldId: {
        required: true,
        value: memberToViewRefFieldIdValue,
      },
      memberToViewRefFieldValue: {
        required: true,
      },
      pairId: {
        required: true,
      },
      viewIdToNavigateOnEndPair: {
        required: true,
        value: 'pair-overview-page',
      },
    },
  });
}
const roleNameMaps = {
  en: {
    group: {
      company: 'Company',
      group: 'Group',
      startup: 'Startup',
    },
    mentee: {
      attendee: 'Attendee',
      candidate: 'Candidate',
      coachee: 'Coachee',
      consultee: 'Consultee',
      entrepreneur: 'Entrepreneur',
      member: 'Member',
      mentee: 'Mentee',
      student: 'Student',
    },
    mentor: {
      alumnus: 'Alumnus',
      angel: 'Angel',
      authority: 'Company Rep.',
      coach: 'Coach',
      consultant: 'Consultant',
      expert: 'Expert',
      host: 'Host',
      mentor: 'Mentor',
      partner: 'Partner',
    },
  },
  tr: {
    group: {
      company: 'Şirket',
      group: 'Grup',
      startup: 'Girişim',
    },
    mentee: {
      attendee: 'Katılımcı',
      candidate: 'Aday',
      coachee: 'Danışan',
      consultee: 'Danışan',
      entrepreneur: 'Girişimci',
      member: 'Üye',
      mentee: 'Menti',
      student: 'Öğrenci',
    },
    mentor: {
      alumnus: 'Mezun',
      angel: 'Melek',
      authority: 'Yetkili',
      coach: 'Koç',
      consultant: 'Danışman',
      expert: 'Uzman',
      host: 'Düzenleyici',
      mentor: 'Mentor',
      partner: 'Partner',
    },
  }
};
const getLocalisedRoleName = (config, accountRole, language, viewingGroups) => {
  const otherRole = accountRole === 'mentor' ? (viewingGroups ? 'group' : 'mentee') : 'mentor';
  const roleNameConstant = accountRole === 'mentor'
    ? (viewingGroups ? config.termReplacements.group : config.termReplacements.mentee)
    : config.termReplacements.mentor;
  return (roleNameMaps[language] || roleNameMaps.en)[otherRole][roleNameConstant];
};

const MentornityPairDetailWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.weekStartDay = 'monday';
  }
  onAction(event) {
    const action = event.detail;
    switch (action.name) {
      case 'send-message':
        window.dispatchEvent(new CustomEvent('dvn.atama-pairs.send-message', {
          detail: {
            user: action.data.item.user,
          }
        }));
        break;
      case 'create-meeting':
        const meetingConfig = action.data.meetingConfig;
        window.dispatchEvent(new CustomEvent('dvn.atama-pairs.create-meeting', {
          detail: {
            goal: {
              identifier: meetingConfig.id,
              meetingTitle: meetingConfig.name,
            },
            user: action.data.item.user,
          }
        }));
        break;
      case 'open-meeting-detail':
        window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-meeting-detail', {
          detail: {
            meetingId: action.data.meeting._id,
          }
        }));
        break;
      case 'open-meeting-detail-from-meeting-list':
        window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-meeting-detail', {
          detail: {
            meetingId: action.params.meetingId,
          }
        }));
        break;
    }
    if (action.type === 'navigation') {
      const { direction, resetHistory, viewId } = action;
      if (direction === 'forward' && resetHistory && viewId === 'pair-overview-page') {
        // user ended the subscription, go to pair list page
        window.dispatchEvent(new CustomEvent('dvn.atama-pairs.open-pair-overview-page', {}));
      }
    }
  }
  async componentWillLoad() {
    const { isZoomAuthenticated, isGoogleAuthenticated, isMicrosoftBusinessAuthenticated, language, timeFormat, dateFormat, timeZone, weekStartDay, } = this;
    // set user's locale and time zone
    calendar.CalendarUtils.setTimeFormat(timeFormat);
    calendar.CalendarUtils.setTimeZone(timeZone);
    calendar.CalendarUtils.setDateFormat(dateFormat);
    switch (language) {
      case 'pt-br':
        calendar.CalendarUtils.setLocale(language, sozlukEntries.sozlukCalendarEntryPtBr, weekStartDay);
        break;
      case 'tr':
        calendar.CalendarUtils.setLocale(language, sozlukEntries.sozlukCalendarEntryTr, weekStartDay);
        break;
      default:
        calendar.CalendarUtils.setLocale(language, sozlukEntries.sozlukCalendarEntryEn, weekStartDay);
        break;
    }
    this.apiSozluk = new index$1.SozlukApi().setLanguage(language).setContents(sozlukEntries.sozlukEntries);
    const { context, headers } = session.getSessionDetails(this.groupId);
    this.mentornityCookieContext = context;
    this.userSettings = session.getUserSettings(timeFormat, dateFormat, timeZone, language, isZoomAuthenticated, isGoogleAuthenticated, isMicrosoftBusinessAuthenticated);
    this.membership = session.generateMembershipForRole(context.role);
    this.mentornityBridgeApi = new mentorintyBridgeApi.MentornityBridgeApi(session.mentornityApiEndpoint, context, headers);
    const mentornityApi = session.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    const user = await mentornityApi.get('users', context.userId)
      .catch(error => this.error = error);
    if (!user)
      return;
    this.user = User.User.decode(user);
    const getViewConfigsResponse = await mentornityApi.getViewConfigs(context.organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    const viewConfigs = getViewConfigsResponse.results;
    const organisationConfig = await mentornityApi.getOrganisationConfig(context.organisationId)
      .catch(error => this.error = error);
    if (!organisationConfig)
      return;
    this.organisationConfig = organisationConfig;
    const goalConfig = await mentornityApi.getOrganisationMeetingGoalConfig(context.organisationDomain)
      .catch(error => this.error = error);
    this.goalConfig = goalConfig;
    this.atamaMemberPairDetailViewConfig = getPairDetailViewConfig(context, language, organisationConfig, goalConfig, viewConfigs);
  }
  render() {
    const { atamaMemberPairDetailViewConfig, membership, mentornityBridgeApi, mentornityCookieContext, organisationConfig, user, userSettings, } = this;
    if (!atamaMemberPairDetailViewConfig) {
      return null;
    }
    const params = getPairDetailParameters(mentornityCookieContext, organisationConfig);
    return (index.h("mentornity-root-wrapper", null, index.h("dvn-app-view-atama-member-pair-detail-view", { apiAtama: mentornityBridgeApi, apiData: mentornityBridgeApi, apiTakvim: mentornityBridgeApi, apiUye: mentornityBridgeApi, apiSozluk: this.apiSozluk, membership: membership, user: user, userSettings: userSettings, params: params, view: atamaMemberPairDetailViewConfig })));
  }
};

exports.mentornity_pair_detail_wrapper = MentornityPairDetailWrapper;
