'use strict';

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

const index = require('./index-ce58ddc5.js');
const dataModel = require('./data-model-9afb7f54.js');
const index$1 = require('./index-b2910095.js');
require('./apiBase-b14a8285.js');
require('./data-transfer-field-0ce05c1a.js');
require('./filter-d5040f65.js');
const instance = require('./instance-fba77445.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-616ff4b9.js');
const env = require('./env-56a21d68.js');
const session = require('./session-fe19e012.js');
const wrapperUtil = require('./wrapper-util-3e4d6318.js');
const sozlukEntries = require('./sozluk-entries-415b953f.js');
const calendar = require('./calendar-12e78fe7.js');
require('./BaseField-d019ade6.js');
require('./FieldModelGenerator-1af8e5c3.js');
require('./reference-field-dda66f2e.js');
require('./index-f92537c9.js');
require('./index-7e3bc620.js');
require('./date-25b104f6.js');
require('./index-9ea6c7b1.js');
require('./index-93271b8c.js');
require('./index-29b7cb16.js');
require('./index-792d710c.js');
require('./index-fa185e3b.js');
require('./attachment-3090e25e.js');
require('./membership-310dd68e.js');
require('./table-config-73a193be.js');
require('./string-de672b69.js');
require('./User-e15e0b6d.js');
require('./CalendarConfig-7f8ef631.js');
require('./UserSettings-fc04eb54.js');
require('./cookie-ea977378.js');
require('./kimlikApi-f4f62100.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./detail-view-config-ba51db6c.js');
require('./view-config-1c8cc7cb.js');
require('./atama-member-pairs-overview-view-config-7d87e3ec.js');
require('./pair-config-6e44fea9.js');
require('./pair-config-278a2924.js');
require('./common-wrapper-util-f504304b.js');
require('./i18n-1b762664.js');
require('./index-1f95aafc.js');
require('./moment-d48a0164.js');

/**
 * Mentornity web-client has the same event name mapping to consume the events with the same name.
 */
const ViewEvents = {
  openProfilePage: 'dvn.mentornity-member-home-widgets-wrapper.open-profile-page',
  openMeetingDetail: 'dvn.mentornity-member-home-widgets-wrapper.open-meeting-page',
  openMenteesPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentees-page',
  openMentorsPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentors-page',
  openUserPairPage: 'dvn.mentornity-member-home-widgets-wrapper.open-user-pair-page',
  openMentorSelectionPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentor-selection-page',
};
let MentornityMemberHomeWidgetsWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.isPairsDataPending = true;
    this.isUpcomingMeetingPending = true;
  }
  componentWillLoad() {
    const { timeFormat, timeZone, } = this;
    // set user's locale and time zone
    calendar.CalendarUtils.setTimeFormat(timeFormat);
    calendar.CalendarUtils.setTimeZone(timeZone);
    this.loadData();
  }
  onAction(event) {
    const action = event.detail;
    switch (action.name) {
      case 'go-to-mentees-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMenteesPage));
        break;
      case 'go-to-mentors-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMentorsPage));
        break;
      case 'go-to-pair-detail-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openUserPairPage, {
          detail: {
            userId: action.params.uid,
            subId: action.params.subId,
          }
        }));
        break;
      case 'go-to-mentor-selection':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMentorSelectionPage));
        break;
      case 'go-to-meeting-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMeetingDetail, {
          detail: {
            meetingId: action.params.meetingId,
          }
        }));
        break;
    }
  }
  async fetchPairs(meetings, mentornityApi, context) {
    const getViewConfigsResponse = await mentornityApi.getViewConfigs(context.organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    const viewConfigs = getViewConfigsResponse.results;
    const view = wrapperUtil.getPairOverviewViewConfig(context, this.language, this.organisationConfig, viewConfigs);
    const membership = dataModel.DataModel.decode({});
    const userRefFieldId = context.role === 'mentor' ? 'subscribed' : 'subscriber';
    const getPairsResponse = await this.mentornityBridgeApi.getPairsOfUser(view.table.base, view.table.name, userRefFieldId, membership._id)
      .catch(error => this.error = error);
    const activePairs = [];
    const requestedPairs = [];
    const pairsType = context.role === 'mentor' ? 'subscriber' : 'subscribed';
    getPairsResponse.results.forEach(pair => {
      if ((pair === null || pair === void 0 ? void 0 : pair.status) === 'active') {
        activePairs.push({
          user: pair[pairsType][0],
          meetings: meetings.filter(meeting => meeting.guests.some(guest => (meeting.status === 'active' && guest._id === pair[pairsType][0]._id)))
        });
      }
      else if ((pair === null || pair === void 0 ? void 0 : pair.status) === 'requested') {
        requestedPairs.push({
          user: pair[pairsType][0],
          meetings: meetings.filter(meeting => meeting.guests.some(guest => guest._id === pair[pairsType][0]._id))
        });
      }
    });
    this.activePairs = activePairs;
    this.requestedPairs = requestedPairs;
    this.isPairsDataPending = false;
  }
  async fetchPairsMeetings(context, mentornityApi) {
    var _a;
    const { organisationDomain, organisationId, userId, groupId } = context;
    this.meetingGoalConfig = await mentornityApi.getOrganisationMeetingGoalConfig(organisationDomain)
      .catch(error => {
      return this.error = error;
    });
    const hasMeetingGoal = this.meetingGoalConfig && ((_a = this.meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
    let meetings;
    if (hasMeetingGoal) {
      meetings = await mentornityApi.getMeetingsInMeetingGoal(organisationDomain, { status: 'active' })
        .catch(error => this.error = error);
      meetings = meetings === null || meetings === void 0 ? void 0 : meetings.results;
    }
    else {
      if (this.userType === 'mentee' && this.menteeType === 'group') {
        meetings = await mentornityApi.getGroupsMeetingsChronologically(groupId, 0)
          .catch(error => this.error = error);
      }
      else {
        meetings = await mentornityApi.getUsersMeetingsChronologically(userId, organisationId, 0)
          .catch(error => this.error = error);
      }
    }
    return meetings;
  }
  async fetchUpcomingMeetings(context, mentornityApi) {
    var _a, _b;
    const hasMeetingGoal = this.meetingGoalConfig && ((_a = this.meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
    let promise;
    if (hasMeetingGoal) {
      promise = mentornityApi.getUsersWithMeetingsInMeetingGoal(context.organisationId, `${this.userType}s`);
    }
    else if (context.groupId) {
      promise = mentornityApi.getGroupsMeetingsChronologically(context.groupId, 0);
    }
    else {
      promise = mentornityApi.getUsersMeetingsChronologically(context.userId, context.organisationId, 0);
    }
    let meetings = await promise.catch(error => this.error = error);
    if (hasMeetingGoal) {
      meetings = (_b = meetings.results.find(user => user._id === context.userId)) === null || _b === void 0 ? void 0 : _b.events;
    }
    const upcomingMeetings = [];
    const today = new Date();
    (meetings || []).forEach((meeting) => {
      const startDate = new Date(meeting.startDate * 1000);
      if (startDate > today && meeting.status !== 'canceled') {
        upcomingMeetings.unshift(meeting);
      }
    });
    this.upcomingMeetings = upcomingMeetings;
    this.isUpcomingMeetingPending = false;
  }
  async loadData() {
    const { context, headers } = session.getSessionDetails(this.groupId);
    const { organisationId } = context;
    // Setup configuration
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
    this.mentornityBridgeApi = new mentorintyBridgeApi.MentornityBridgeApi(env.mentornityApiEndpoint, context, headers);
    const mentornityApi = instance.createMentornityApiInstance(env.mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      this.organisationConfig = instance.Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = instance.Config.decode(response);
    });
    // Fetch data from api
    const meetings = await this.fetchPairsMeetings(context, mentornityApi);
    await this.fetchPairs(meetings, mentornityApi, context);
    await this.fetchUpcomingMeetings(context, mentornityApi);
  }
  render() {
    const { activePairs, apiSozluk, isPairsDataPending, menteeType, meetingGoalConfig, organisationConfig, requestedPairs, userType, mentorMenteeSubscription, upcomingMeetings, isUpcomingMeetingPending, } = this;
    const showPairsWidget = mentorMenteeSubscription === "restricted";
    return (index.h(index.Host, null, index.h("mentornity-root-wrapper", { class: "d-block pt-4", theme: { cornerRadius: '5px' } }, showPairsWidget &&
      index.h("mentornity-pair-meeting-summary-widget", { apiSozluk: apiSozluk, isPending: isPairsDataPending, activePairs: activePairs, organisationConfig: organisationConfig, meetingGoalConfig: meetingGoalConfig, requestedPairs: requestedPairs, userType: userType, menteeType: menteeType }), index.h("mentornity-upcoming-meetings-widget", { meetings: upcomingMeetings, meetingGoalConfig: this.meetingGoalConfig, isPending: isUpcomingMeetingPending, timeFormat: this.timeFormat, apiSozluk: apiSozluk, userType: userType }))));
  }
};

exports.mentornity_member_home_widgets_wrapper = MentornityMemberHomeWidgetsWrapper;
