'use strict';

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

const index = require('./index-1141a245.js');
const dataModel = require('./data-model-9afb7f54.js');
const calendar = require('./calendar-e4b7baeb.js');
const index$1 = require('./index-a2e99c85.js');
require('./apiBase-e4ebaf8b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const instance = require('./instance-36d7564f.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-0534712d.js');
const session = require('./session-b6f20e12.js');
const wrapperUtil = require('./wrapper-util-1d4e0a9d.js');
require('./index-b776fc14.js');
require('./_commonjsHelpers-206db00d.js');
require('./moment-7a3433f2.js');
require('./BaseField-381327a9.js');
require('./FieldModelGenerator-1900d81a.js');
require('./reference-field-1239b0c3.js');
require('./index-2eea69a0.js');
require('./FieldGenerator-279a646b.js');
require('./date-a24d7714.js');
require('./index-0783d14f.js');
require('./index-e8e4d80b.js');
require('./index-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./index-61f9621a.js');
require('./index-e751cab0.js');
require('./attachment-b0acc4c1.js');
require('./membership-ed8d3277.js');
require('./table-config-8b14c7d3.js');
require('./string-de672b69.js');
require('./User-e889279b.js');
require('./CalendarConfig-ee7bb722.js');
require('./UserSettings-fc04eb54.js');
require('./cookie-135bf612.js');
require('./kimlik-api-d3c479a3.js');
require('./index-33e96540.js');
require('./i18n-49870fc9.js');
require('./i18n-5585a319.js');
require('./detail-view-config-4fe32db3.js');
require('./view-config-7972654b.js');
require('./atama-member-pairs-overview-view-config-3a953766.js');
require('./pair-config-0f8299eb.js');
require('./pair-config-c81aa77f.js');
require('./common-wrapper-util-a539b2ff.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',
};
const MentornityMemberHomeWidgetsWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.isPairsDataPending = true;
    this.isMeetingPending = true;
    this.isAnnouncementsPending = true;
    this.isOrganisationDataPending = 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;
    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 fetchPastMeeings(context) {
    let promise;
    if (context.groupId) {
      promise = this.api.getGroupsMeetingsChronologically(context.groupId, 0);
    }
    else {
      promise = this.api.getUsersMeetingsChronologically(this.context.userId, this.context.organisationId, 0);
    }
    let meetings = await promise.catch(error => this.error = error);
    const pastMeetings = [];
    let unfilledFormCount = 0;
    const today = new Date();
    (meetings || []).forEach((meeting) => {
      const startDate = new Date(meeting.startDate * 1000);
      if (startDate < today && meeting.status !== 'canceled') {
        if (!(meeting === null || meeting === void 0 ? void 0 : meeting.feedback))
          unfilledFormCount++;
        pastMeetings.unshift(meeting);
      }
    });
    return {
      meetings: pastMeetings,
      unfilledFormCount
    };
  }
  async fetchUserMeetings(context, mentornityApi) {
    var _a;
    let promise;
    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);
    const hasMeetingGoal = this.meetingGoalConfig && ((_a = this.meetingGoalConfig.meetingGoals) === null || _a === void 0 ? void 0 : _a.length) > 0;
    const upcomingMeetings = [];
    const pastMeetings = [];
    let unfilledFormCount = 0;
    let unfilledSessionFormCount = 0;
    const today = new Date();
    (meetings || []).forEach((meeting) => {
      var _a, _b, _c, _d, _e, _f, _g;
      const startDate = new Date(meeting.startDate * 1000);
      if (startDate >= today && meeting.status !== 'canceled') {
        upcomingMeetings.unshift(meeting);
      }
      if (startDate < today && meeting.status !== 'canceled') {
        if (!(meeting === null || meeting === void 0 ? void 0 : meeting.feedback))
          unfilledFormCount++;
        // calculate unfilled session forms
        if (hasMeetingGoal) {
          let sessionHasQuestions = false;
          const ownSession = hasMeetingGoal && ((_a = this.meetingGoalConfig) === null || _a === void 0 ? void 0 : _a.meetingGoals.find(session => session.identifier === meeting.meetingGoalIdentifier));
          const session = ownSession === null || ownSession === void 0 ? void 0 : ownSession.specifications[this.userType];
          sessionHasQuestions = ((_c = (_b = session === null || session === void 0 ? void 0 : session.postMeetingForm) === null || _b === void 0 ? void 0 : _b.fields) === null || _c === void 0 ? void 0 : _c.length) > 0 || ((_e = (_d = session === null || session === void 0 ? void 0 : session.preMeetingForm) === null || _d === void 0 ? void 0 : _d.fields) === null || _e === void 0 ? void 0 : _e.length) > 0;
          const hasFeedback = !!((_f = meeting === null || meeting === void 0 ? void 0 : meeting.feedback) === null || _f === void 0 ? void 0 : _f._id) || ((_g = meeting === null || meeting === void 0 ? void 0 : meeting.feedback) === null || _g === void 0 ? void 0 : _g.length) > 0;
          if (sessionHasQuestions && !hasFeedback)
            unfilledSessionFormCount++;
        }
        pastMeetings.unshift(meeting);
      }
    });
    this.upcomingMeetings = upcomingMeetings;
    this.pastMeetings = pastMeetings;
    this.unfilledSessionFormCount = unfilledSessionFormCount;
    this.unfilledFormCount = unfilledFormCount;
    this.isMeetingPending = false;
  }
  async fetchAnnouncements(mentornityApi) {
    const { organisationId, role } = this.context;
    // Fetch announcements from api
    this.announcements = await mentornityApi.getAnnouncements(organisationId, role);
    this.isAnnouncementsPending = false;
  }
  async fetchOrganisation(mentornityApi) {
    this.organisation = await mentornityApi.getOrganisation(this.organisationConfig.organisation._id);
    this.isOrganisationDataPending = false;
  }
  async loadData() {
    const { context, headers } = session.getSessionDetails(this.groupId);
    const { organisationId } = context;
    const showPairsWidget = this.mentorMenteeSubscription === 'restricted';
    // Setup configuration
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(session.sozlukEntries);
    this.mentornityBridgeApi = new mentorintyBridgeApi.MentornityBridgeApi(session.mentornityApiEndpoint, context, headers);
    const mentornityApi = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      this.organisationConfig = instance.Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = instance.Config.decode(response);
    });
    this.api = mentornityApi;
    this.context = context;
    this.sessionData = await mentornityApi.getSessionData(context.organisationDomain);
    this.meetingGoalConfig = await mentornityApi.getOrganisationMeetingGoalConfig(context.organisationDomain)
      .catch(error => this.error = error);
    // Fetch data from api
    const meetings = await this.fetchPairsMeetings(context, mentornityApi);
    if (showPairsWidget) {
      this.fetchPairs(meetings, mentornityApi, context);
    }
    this.fetchUserMeetings(context, mentornityApi);
    this.fetchOrganisation(mentornityApi);
    this.fetchAnnouncements(mentornityApi);
  }
  render() {
    const { activePairs, apiSozluk, isPairsDataPending, menteeType, meetingGoalConfig, organisationConfig, requestedPairs, userType, mentorMenteeSubscription, upcomingMeetings, pastMeetings, unfilledFormCount, unfilledSessionFormCount, isMeetingPending, sessionData, groupId, context, api, announcements, isAnnouncementsPending, isOrganisationDataPending, organisation } = this;
    const showPairsWidget = mentorMenteeSubscription === 'restricted';
    const feedbackConfig = (organisationConfig && organisationConfig.feedback) && (organisationConfig === null || organisationConfig === void 0 ? void 0 : organisationConfig.feedback[userType]);
    return (index.h(index.Host, null, index.h("mentornity-root-wrapper", { class: "d-block pt-4", theme: { cornerRadius: '15px' } }, index.h("div", { class: "row" }, index.h("div", { class: "col-md-8 order-2 order-md-1" }, 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, account: sessionData === null || sessionData === void 0 ? void 0 : sessionData.account, groupId: groupId, isPending: isMeetingPending, timeFormat: this.timeFormat, apiSozluk: apiSozluk }), index.h("mentornity-past-meetings-widget", { meetings: pastMeetings, meetingGoalConfig: this.meetingGoalConfig, fetchPastMeetings: this.fetchPastMeeings, context: context, userType: userType, unfilledFormCount: unfilledFormCount, unfilledSessionFormCount: unfilledSessionFormCount, account: sessionData === null || sessionData === void 0 ? void 0 : sessionData.account, groupId: groupId, isPending: isMeetingPending, timeFormat: this.timeFormat, apiSozluk: apiSozluk, feedbackConfig: feedbackConfig, api: api })), index.h("div", { class: "col-md-4 order-1 order-md-2" }, index.h("mentornity-announcements-widget", { announcements: announcements, isPending: isAnnouncementsPending, apiSozluk: apiSozluk }), index.h("mentornity-program-info-widget", { organisation: organisation, organisationConfig: organisationConfig, isPending: isOrganisationDataPending, apiSozluk: apiSozluk }))))));
  }
};

exports.mentornity_member_home_widgets_wrapper = MentornityMemberHomeWidgetsWrapper;
