import { r as registerInstance, h, H as Host } from './index-b7735e0d.js';
import { D as DataModel } from './data-model-f7ccf826.js';
import { S as SozlukApi } from './index-1e9f4c53.js';
import './apiBase-d573f009.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { c as createMentornityApiInstance, b as Config } from './instance-7b02ef1d.js';
import { M as MentornityBridgeApi } from './mentorinty-bridge-api-78ab1153.js';
import { m as mentornityApiEndpoint } from './env-4ec3c807.js';
import { g as getSessionDetails } from './session-b16a440c.js';
import { g as getPairOverviewViewConfig } from './wrapper-util-b6f35106.js';
import { s as sozlukEntries } from './sozluk-entries-849428da.js';
import { C as CalendarUtils } from './calendar-67e174ec.js';
import './BaseField-461b6d0c.js';
import './FieldModelGenerator-020f4a04.js';
import './reference-field-0e7cd534.js';
import './index-7b119e61.js';
import './index-403101cb.js';
import './date-ce777316.js';
import './index-1d3efe49.js';
import './index-eb14fd2d.js';
import './index-80ec23ef.js';
import './index-4c39b6a6.js';
import './index-774783ee.js';
import './attachment-32decf79.js';
import './membership-e92743d1.js';
import './table-config-0c06fb1f.js';
import './string-3065a411.js';
import './User-1ef5a482.js';
import './CalendarConfig-88c2213e.js';
import './UserSettings-27df01e6.js';
import './cookie-1686830b.js';
import './kimlikApi-0d7e6ce7.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './detail-view-config-59c98d8d.js';
import './view-config-dfb61752.js';
import './atama-member-pairs-overview-view-config-83ec05c4.js';
import './pair-config-f92eeeb7.js';
import './pair-config-cf56a965.js';
import './common-wrapper-util-289d199c.js';
import './i18n-e90027e3.js';
import './index-3958847a.js';
import './moment-6f6ab70c.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) {
    registerInstance(this, hostRef);
    this.isPairsDataPending = true;
    this.isUpcomingMeetingPending = true;
  }
  componentWillLoad() {
    const { timeFormat, timeZone, } = this;
    // set user's locale and time zone
    CalendarUtils.setTimeFormat(timeFormat);
    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 = getPairOverviewViewConfig(context, this.language, this.organisationConfig, viewConfigs);
    const membership = 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 } = getSessionDetails(this.groupId);
    const { organisationId } = context;
    // Setup configuration
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    this.mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      this.organisationConfig = Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = 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 (h(Host, null, h("mentornity-root-wrapper", { class: "d-block pt-4", theme: { cornerRadius: '5px' } }, showPairsWidget &&
      h("mentornity-pair-meeting-summary-widget", { apiSozluk: apiSozluk, isPending: isPairsDataPending, activePairs: activePairs, organisationConfig: organisationConfig, meetingGoalConfig: meetingGoalConfig, requestedPairs: requestedPairs, userType: userType, menteeType: menteeType }), h("mentornity-upcoming-meetings-widget", { meetings: upcomingMeetings, meetingGoalConfig: this.meetingGoalConfig, isPending: isUpcomingMeetingPending, timeFormat: this.timeFormat, apiSozluk: apiSozluk, userType: userType }))));
  }
};

export { MentornityMemberHomeWidgetsWrapper as mentornity_member_home_widgets_wrapper };
