var __rest = (this && this.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
import { APIBase } from '@dvn/core/api/apiBase';
import { generateFieldModelFromRawData } from '@dvn/core/doldurma/src/FieldModelGenerator';
import { AttachmentField } from '@dvn/core/doldurma/src/fields/attachment';
import { MultipleChoiceField } from '@dvn/core/doldurma/src/fields/multiple-choice';
import { RangeField } from '@dvn/core/doldurma/src/fields/range';
import { ReferenceField } from '@dvn/core/doldurma/src/fields/reference';
import { SingleChoiceField } from '@dvn/core/doldurma/src/fields/single-choice';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { DataModel } from '@dvn/core/models/data-model';
import { Membership } from '@dvn/core/models/membership';
import { MembershipConfig } from '@dvn/core/models/membership-config';
import { User } from '@dvn/kimlik/api/models';
import { CalendarConfig } from '@dvn/takvim/api/models';
import skills from '../constants/skills';
import skillsEN from '../constants/skills-en';
import skillsPtBr from '../constants/skills-pt-br';
import skillsTr from '../constants/skills-tr';
import { generateMembershipConfigForRole } from '../util/session';
function getRequestStatus(request) {
  if (request.status === 'completed') {
    return 'completed';
  }
  if (request.rejectedAt) {
    return 'rejected';
  }
  else if (request.canceledAt) {
    return 'canceled';
  }
  else if (request.acceptedAt) {
    return 'accepted';
  }
  else if (request.requestedAt) {
    return 'requested';
  }
}
export const embeddedTranslations = {
  en: {
    title: 'Title',
    bio: 'Bio',
    skills: 'Professional Expertise',
    search: 'Search',
    goToProfilePage: 'Go to Profile Page',
    info: 'Info',
    getMeeting: 'Get Meeting',
    viewDetails: 'View Details',
    meetings: 'Meetings',
    follow: 'Follow',
    unfollow: 'Unfollow',
    sendMessage: 'Send Message'
  },
  'pt-br': {
    title: 'Titulo',
    bio: 'Bio',
    skills: 'Expertise profissional',
    search: 'Buscar',
    goToProfilePage: 'Vá para a página do perfil',
    info: 'Informação',
    getMeeting: 'Agendar Sessões',
    viewDetails: 'Ver detalhes',
    meetings: 'Sessões',
    follow: 'Seguir',
    unfollow: 'Deixar de seguir',
    sendMessage: 'Enviar mensagem'
  },
  tr: {
    title: 'Ünvan',
    bio: 'Özgeçmiş',
    skills: 'Uzmanlık alanları',
    search: 'Ara',
    goToProfilePage: 'Profil Sayfasına Git',
    info: 'Bilgi',
    getMeeting: 'Toplantı Oluştur',
    viewDetails: 'Detayları Gör',
    meetings: 'Toplantılar',
    follow: 'Takip Et',
    unfollow: 'Takibi Bırak',
    sendMessage: 'Mesaj Gönder'
  },
};
export function getEmbeddedTranslation(language, key) {
  return (embeddedTranslations[language] || embeddedTranslations.en)[key];
}
export const legacyProfileFields = (language = 'en') => {
  const strings = embeddedTranslations[language] || embeddedTranslations.en;
  let skillStrings = skillsEN;
  switch (language) {
    case 'pt-br':
      skillStrings = skillsPtBr;
      break;
    case 'tr':
      skillStrings = skillsTr;
      break;
  }
  return [
    generateFieldModelFromRawData({ id: 'title', title: strings.title, type: 'text' }),
    generateFieldModelFromRawData({ id: 'bio', title: strings.bio, type: 'text', lines: 3 }),
    generateFieldModelFromRawData({
      id: 'skills',
      title: strings.skills,
      type: 'multiple-choice',
      inputType: 'tag-cloud',
      options: skills.map(skill => ({
        label: skillStrings[skill] || skill, value: skill,
      })),
    }),
  ];
};
export const commonUserInfoFields = [
  generateFieldModelFromRawData({ id: 'name', type: 'text' }),
  generateFieldModelFromRawData({ id: 'imageUrl', type: 'image' }),
  generateFieldModelFromRawData({ id: 'title', title: 'Title', type: 'text' }),
  generateFieldModelFromRawData({ id: 'bio', title: 'Bio', type: 'text', lines: 3 }),
  generateFieldModelFromRawData({ id: 'imagePlaceholderValue', title: '', type: 'text' }),
  generateFieldModelFromRawData({
    id: 'skills',
    title: 'Professional Expertise',
    type: 'multiple-choice',
    inputType: 'tag-cloud',
    options: skills.map(skill => ({
      label: skillsEN[skill], value: skill,
    })),
  }),
];
export const groupInfoFields = [
  generateFieldModelFromRawData({ id: 'imageUrl', type: 'image' }),
  generateFieldModelFromRawData({ id: 'title', title: 'Title', type: 'text' }),
  generateFieldModelFromRawData({ id: 'description', title: 'Description', type: 'text', lines: 3 }),
  generateFieldModelFromRawData({ id: 'imagePlaceholderValue', title: '', type: 'text' }),
  new ReferenceField('members', 'Members', 'name', 'imageUrl', 'users', [
    new AttachmentField('imageUrl', ''),
    new TextField('firstName', 'First Name'),
    new TextField('lastName', 'Last Name'),
    new TextField('name', 'Name'),
  ], false),
];
function getQueryParamValueFromNestedFilter(filter) {
  if (!filter) {
    return {};
  }
  if (filter === null || filter === void 0 ? void 0 : filter.filters) {
    let nestedValues = {};
    filter.filters.forEach(f => {
      nestedValues = Object.assign(nestedValues, getQueryParamValueFromNestedFilter(f));
    });
    return nestedValues;
  }
  if (!filter.id) {
    return {};
  }
  return {
    [filter.id]: filter.value,
  };
}
function convertDevingenQueryToMemberListQuery(query) {
  // console.log(JSON.stringify(query.filter, null, 2));
  const { limit = 25, skip = 0 } = query;
  const mentornityMemberListQuery = {
    limit, skip,
  };
  const filterValuesFromUI = getQueryParamValueFromNestedFilter(query.filter);
  const fieldIds = Object.keys(filterValuesFromUI);
  fieldIds.forEach(fieldId => {
    if (['search', 'title', 'bio', 'skills'].includes(fieldId)) {
      mentornityMemberListQuery[fieldId] = filterValuesFromUI[fieldId];
    }
    else {
      mentornityMemberListQuery[`metadata.data.${fieldId}`] = filterValuesFromUI[fieldId];
    }
  });
  // console.log(mentornityMemberListQuery);
  return mentornityMemberListQuery;
}
export function convertMentornityFieldToDevingenField(field) {
  let dvnField;
  if (field.type === 'ratingStars') {
    dvnField = new RangeField(field.id, field.title, field.description, 0.2, 0.2, 1).setInputType('stars');
  }
  else if (field.type === 'singleChoice') {
    dvnField = new SingleChoiceField(field.id, field.title, field.options, field.description, field.inputType, field.placeholder);
  }
  else if (field.type === 'multipleChoice') {
    dvnField = new MultipleChoiceField(field.id, field.title, field.options, field.description, field.inputType, field.placeholder);
  }
  else {
    dvnField = generateFieldModelFromRawData(field);
  }
  if (field.required) {
    dvnField.require();
  }
  return dvnField;
}
function convertDevingenRefToMentornityRef(ref) {
  return {
    _id: ref._id,
    _class: ref._ref,
    _type: 'reference'
  };
}
function convertDevingenEventToMentornityEvent(context, organisationConfig, event) {
  var _a, _b;
  const { organisationId, userId, role } = context;
  const currentUserAsGuest = event.guests.find(guest => guest._id === userId);
  const otherGuest = event.guests.find(guest => guest._id !== userId);
  if (organisationConfig.menteeType === 'group') {
    // convert the reference class to groups if the mentee type is group
    if (role === 'mentor') {
      // other user must be groups
      otherGuest._ref = 'groups';
    }
    else {
      // mentee is creating the meeting as the group
      currentUserAsGuest._ref = 'groups';
      currentUserAsGuest._id = context.groupId;
    }
  }
  // first user in the array must be mentor ref
  const guests = role === 'mentor' ? [currentUserAsGuest, otherGuest] : [otherGuest, currentUserAsGuest];
  return {
    location: (((_a = event.locations) === null || _a === void 0 ? void 0 : _a[0]) || {}),
    createdBy: convertDevingenRefToMentornityRef(event.createdBy),
    organisation: {
      _id: organisationId,
      _class: 'organisations',
      _type: 'reference'
    },
    availability: {
      _id: (_b = event.availability) === null || _b === void 0 ? void 0 : _b._id,
      _class: 'availabilities',
      _type: 'reference'
    },
    guests: guests.map(guest => ({
      _id: guest._id,
      _class: guest._ref === 'kimlik-users' ? 'users' : guest._ref,
      _type: 'reference'
    })),
    type: 'meeting',
    status: 'active',
    meetingGoalIdentifier: event.meetingType,
    startDate: new Date(event.startDate).getTime() / 1000,
    endDate: new Date(event.endDate).getTime() / 1000,
  };
}
export function generateCalendarConfig(config) {
  const { meetingSettings } = config;
  const canMentorsCreateAvailability = !!meetingSettings.mentorsCanCreateAvailability;
  const canMenteesCreateMeeting = !!meetingSettings.menteesCanCreateMeeting;
  const canMentorsCreateMeeting = !!meetingSettings.mentorsCanCreateMeeting;
  return CalendarConfig.decode({
    _id: 'mentornity-calendar-config',
    membershipPreferences: [
      {
        membershipConfig: generateMembershipConfigForRole('mentor'),
        canCreateAvailableTime: canMentorsCreateAvailability,
        eligibleMembershipsForCustomTime: !canMenteesCreateMeeting ? [] : [
          generateMembershipConfigForRole('mentee'),
        ]
      },
      {
        membershipConfig: generateMembershipConfigForRole('mentee'),
        canCreateAvailableTime: false,
        eligibleMembershipsForCustomTime: !canMentorsCreateMeeting ? [] : [
          generateMembershipConfigForRole('mentor'),
        ]
      },
    ]
  });
}
export class MentornityBridgeApi {
  constructor(endpoint, context, headers) {
    this.client = new APIBase(endpoint, headers);
    this.context = context;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // DATA API
  get(collection, id, _query) {
    // console.log('MBA.get', collection, id, _query);
    const { organisationId } = this.context;
    if (collection === 'groups') {
      return new Promise((resolve => {
        this.client.get(`groups/${id}`).then(response => {
          resolve(DataModel.decode(Object.assign(Object.assign({ 
            // dvn-app-view-atama-member-pair-detail-view expects 'user' field in the 'membership' object
            user: {
              // id is needed here because the user object is sent to web-client when create meeting is clicked
              _id: response._id,
              firstName: response.title,
              lastName: ' ',
            } }, response), { members: (response.members || []).map(member => (Object.assign(Object.assign({}, member), { name: `${member.firstName} ${member.lastName}` }))) })));
        }).catch(_e => {
          // console.log(e);
        });
      }));
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/${collection}/${id}`).then(response => {
        var _a;
        // separate metadata and user data. consider title, bio and skills as metadata
        const { metadata, title, bio, skills } = response, rest = __rest(response, ["metadata", "title", "bio", "skills"]);
        resolve(DataModel.decode(Object.assign(Object.assign({ user: User.decode(rest) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills })));
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  query(collection, query) {
    if (['mentees', 'mentors'].includes(collection)) {
      // this request is called by dvn-app-view-detail-view-card that is opened
      // when mentor clicks on the mentee info inside the received requests list
      const { organisationId } = this.context;
      const menteeId = query.filter.value;
      return new Promise((resolve => {
        this.client.get(`organisations/${organisationId}/${collection}/${menteeId}`).then(response => {
          var _a;
          // separate metadata and user data. consider title, bio and skills as metadata
          const { metadata, title, bio, skills } = response, rest = __rest(response, ["metadata", "title", "bio", "skills"]);
          resolve({
            results: [
              DataModel.decode(Object.assign(Object.assign(Object.assign({ name: `${response.firstName} ${response.lastName}`, user: User.decode(rest) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills }), rest))
            ]
          });
        }).catch(e => {
          console.log(e);
        });
      }));
    }
    else if (['mentee-card-list', 'mentor-card-list'].includes(collection)) {
      const queryParams = convertDevingenQueryToMemberListQuery(query);
      // this request is called by mentornity-user-card-list-wrapper that is shown
      // for the mentee and mentor list pages
      const { organisationId } = this.context;
      const collectionToQuery = collection === 'mentee-card-list' ? 'mentees' : 'mentors';
      return new Promise((resolve => {
        this.client.get(`organisations/${organisationId}/${collectionToQuery}`, Object.assign({ appendAvailabilities: true, appendSubscription: true, expandMetadatas: true }, queryParams)).then(response => {
          var _a;
          // separate metadata and user data. consider title, bio and skills as metadata
          resolve({
            meta: {
              total: ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) || 0,
            },
            results: response.results.map((user) => {
              const { metadata, title, bio, skills, // membership data
              _id, email, firstName, lastName, imageUrl, // profile data
              availabilities, } = user;
              // auto generated values. used in cardViewConfig
              const name = `${user.firstName} ${user.lastName}`;
              const initials = `${user.firstName[0]}${user.lastName[0]}`;
              return Membership.decode(Object.assign(Object.assign({ 
                // user id is used as membership id too
                _id }, ((metadata === null || metadata === void 0 ? void 0 : metadata.data) || {})), { title, bio, skills, 
                // user data
                user: { _id, email, firstName, lastName, imageUrl, name, initials }, 
                // used by mentornity-schedule-meeting-button-on-card in mentor card list
                availabilities }));
            }).sort((a, b) => a.user.name.localeCompare(b.user.name))
          });
        }).catch(e => {
          console.log(e);
        });
      }));
    }
    return Promise.resolve(undefined);
  }
  update(_collection, _id, _body) {
    return Promise.reject({ status: 418 });
  }
  // ATAMA API
  getPairsOfUser(_base, _collection, userRefFieldId, _userRefFieldValue) {
    // console.log('MBA.getPairsOfUser', base, collection, userRefFieldId, userRefFieldValue);
    const { organisationId } = this.context;
    const { menteeType } = this.organisationConfig;
    // if user reference field is subscribed, then it's a mentor viewing its mentees
    const listToFetch = userRefFieldId === 'subscribed'
      ? (menteeType === 'group' ? 'groups' : 'mentees')
      : 'mentors';
    const itemNameToReturn = userRefFieldId === 'subscribed' ? 'subscriber' : 'subscribed';
    const params = listToFetch === 'groups'
      ? { expandCreatedBy: false }
      : { expandMetadatas: true, appendSubscription: true, };
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/${listToFetch}`, params).then(response => {
        // console.log('response', response);
        setTimeout(() => resolve({
          results: response.results
            // show only the active pairs
            .filter(item => { var _a; return ((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.status) === 'active'; })
            .map(item => {
            var _a;
            return ({
              [itemNameToReturn]: [Object.assign(Object.assign(Object.assign({}, item), (((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { name: `${item.firstName} ${item.lastName}`, imagePlaceholderValue: listToFetch === 'groups'
                    ? ((item.title && item.title.length > 0) ? item.title[0] : '')
                    : `${item.firstName[0]} ${item.lastName[0]}` })],
              status: item.subscription.status,
            });
          }),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  getSelectionList(_base, _collection, _pairConfigId, _userRefFieldId, _memberToViewRefFieldId) {
    // console.log('MBA.getSelectionList', base, collection, pairConfigId, userRefFieldId, memberToViewRefFieldId);
    const { organisationId } = this.context;
    return new Promise(resolve => {
      this.client.get(`organisations/${organisationId}/mentors/selection`).then(response => resolve({
        results: response.results.map(item => {
          var _a;
          return (Object.assign(Object.assign(Object.assign({}, item), (((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { name: `${item.firstName} ${item.lastName}` }));
        })
      })).catch(_e => {
        // console.log(e);
      });
    });
  }
  getSentRequests(_base, _collection, _userRefFieldValue) {
    // console.log('MBA.getSentRequests', base, collection, userRefFieldValue);
    const { organisationId } = this.context;
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentors`, { appendRequestSubscriptions: true, limit: 1000 }).then(response => {
        // console.log('response', response);
        setTimeout(() => resolve({
          results: response.results
            // subscription must contain 'requestedAt' field if this subscription is created via selection request
            .filter(item => { var _a; return !!((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.requestedAt); })
            .map(item => ({
            sentTo: User.decode(item),
            status: getRequestStatus(item.subscription),
            requestedAt: item.subscription.requestedAt,
            acceptedAt: item.subscription.acceptedAt,
            rejectedAt: item.subscription.rejectedAt,
            canceledAt: item.subscription.canceledAt,
          })),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  getReceivedRequests(_base, _collection) {
    // console.log('MBA.getReceivedRequests', base, collection);
    const { organisationId } = this.context;
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentees`, { expandMetadatas: true, limit: 1000 }).then(response => {
        setTimeout(() => resolve({
          results: response.results
            // subscription must contain 'requestedAt' field if this subscription is created via selection request
            .filter(item => { var _a; return !!((_a = item.subscription) === null || _a === void 0 ? void 0 : _a.requestedAt); })
            // show only pending requests
            .sort((a, b) => b.subscription.createdAt - a.subscription.createdAt)
            .map(item => ({
            _id: item.subscription._id,
            sentBy: User.decode(item),
            status: getRequestStatus(item.subscription),
            requestedAt: item.subscription.requestedAt,
            acceptedAt: item.subscription.acceptedAt,
            rejectedAt: item.subscription.rejectedAt,
            canceledAt: item.subscription.canceledAt,
          })),
          meta: response.meta,
        }), 100);
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  sendPairRequest(_base, _collection, _userRefFieldId, userRefFieldValue, _memberToViewRefFieldId, memberToViewData) {
    // console.log('MBA.endPair', base, collection, pairId);
    const { organisationId } = this.context;
    const subscription = {
      mentorship: { _type: 'reference', _class: 'mentorships', _id: memberToViewData.mentorship._id },
      organisation: { _type: 'reference', _class: 'organisations', _id: organisationId },
      subscribed: { _type: 'reference', _class: 'users', _id: memberToViewData._id },
      subscriber: { _type: 'reference', _class: 'users', _id: userRefFieldValue },
      status: 'requested',
    };
    return this.client.post(`subscriptions`, subscription);
    // return Promise.reject({ status: 409 });
  }
  acceptPairRequest(_base, _collection, requestId) {
    return this.client.post(`subscriptions/${requestId}/accept`, {});
  }
  rejectPairRequest(_base, _collection, requestId) {
    return this.client.post(`subscriptions/${requestId}/reject`, {});
  }
  // getMeetingsOfUser(_base: string, _collection: string, _structureId: string, _userRefFieldValue: string): Promise<GetListResponse<DataModel>> {
  //   // console.log('MBA.getMeetingsOfUser', base, collection, structureId, userRefFieldValue);
  //
  //   // the response contains all the meetings with different users
  //   // here we filter the events based on the user id we're viewing
  //   const userIdToView = new URLSearchParams(window.location.search).get('uid');
  //
  //   return new Promise((async resolve => {
  //     const response = await this.client.get<any>(
  //       `organisations/${this.context.organisationDomain}/meetingsInMeetingGoal`,
  //     );
  //     resolve({
  //       results: response.results.filter(meeting => meeting.guests.some(guest => guest._id === userIdToView))
  //     });
  //   }));
  // }
  endPair(_base, _collection, pairId) {
    // console.log('MBA.endPair', base, collection, pairId);
    return new Promise((async (resolve) => {
      const response = await this.client.post(`subscriptions/${pairId}/complete`, {});
      resolve(response);
    }));
  }
  // UYE API
  getAppConfigOfMembership(_id) {
    // console.log('MBA.getAppConfigOfMembership', id);
    return Promise.reject({ status: 418 });
  }
  consentAgreement(_id) {
    // console.log('MBA.consentAgreement', id);
    return Promise.reject({ status: 418 });
  }
  getAgreement(_id) {
    // console.log('MBA.getAgreement', id);
    return Promise.reject({ status: 418 });
  }
  activateMembership(_membershipConfigId, _membershipId) {
    // console.log('MBA.getMembership', id);
    return Promise.reject({ status: 418 });
  }
  getMembership(_membershipConfigId, _membershipId) {
    // console.log('MBA.getMembership', id);
    return Promise.reject({ status: 418 });
  }
  getMembershipsOfUser(_userId) {
    // console.log('MBA.getMembershipsOfUser', userId);
    return Promise.reject({ status: 418 });
  }
  getMembershipConfig(id) {
    console.log('MBA.getMembershipConfig', id);
    return Promise.reject({ status: 418 });
  }
  getMembershipConfigWithName(name) {
    // console.log('MBA.getMembershipConfigWithName', name);
    const { organisationId } = this.context;
    return new Promise((async (resolve) => {
      this.client.get(`organisations/${organisationId}/config`).then(organisationConfig => {
        this.organisationConfig = organisationConfig;
        let fields = [];
        let roleName = '';
        if (name === 'mentees') {
          roleName = 'mentee';
          fields = [
            ...commonUserInfoFields,
            ...organisationConfig.metadatas.mentee
              .map(convertMentornityFieldToDevingenField),
          ];
        }
        else if (name === 'mentors') {
          roleName = 'mentor';
          fields = [
            ...commonUserInfoFields,
            ...organisationConfig.metadatas.mentor
              .map(convertMentornityFieldToDevingenField),
          ];
        }
        else if (name === 'groups') {
          roleName = 'mentee';
          fields = [
            ...groupInfoFields,
          ];
        }
        resolve(MembershipConfig.decode({
          _id: name,
          roleName,
          fields,
        }));
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  updateMembership(_membershipConfigId, _membershipId, _data) {
    // console.log('MBA.updateMembership', id, data);
    return Promise.reject({ status: 418 });
  }
  getAvailabilities(_availabilityConfigId) {
    return Promise.reject({ status: 418 });
  }
  getAvailabilitiesOfUser(_calendarConfigId, userId) {
    const { organisationId, role } = this.context;
    if (role === 'mentor') {
      // mentor is viewing mentee's calendar. return empty availability list
      return Promise.resolve({ results: [] });
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${organisationId}/mentors/${userId}/availabilities`).then(response => {
        resolve({
          results: response.results
            .map(item => (Object.assign(Object.assign({}, item), { breakDuration: item.meetingBreaks, location: item.location.address, locationType: item.location.type, startDate: new Date(item.startDate * 1000), endDate: new Date(item.endDate * 1000) }))),
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  getCalendarConfig(_id) {
    return Promise.resolve(generateCalendarConfig(this.organisationConfig));
  }
  getMeetingsOfUser(calendarConfigId, guestIDs) {
    if (calendarConfigId === 'mentornity-calendar-config') {
      return new Promise((async (resolve) => {
        const { groupId, organisationId, userId } = this.context;
        const isFetchingGroupMeetings = !!groupId;
        const idToUse = isFetchingGroupMeetings ? groupId : userId;
        const collectionToUse = isFetchingGroupMeetings ? 'groups' : 'users';
        const userIdToView = guestIDs.filter(id => id !== idToUse)[0];
        const response = await this.client.get(`${collectionToUse}/${idToUse}/events`, { organisationId: organisationId, limit: 1000 });
        resolve({
          results: response.results
            .filter(meeting => meeting.guests.some(guest => guest._id === userIdToView))
            .filter(meeting => meeting.status === 'active')
            .map(meeting => (Object.assign(Object.assign({}, meeting), { 
            // add 'name' field for users and groups for displaying their name on the meeting list
            guests: meeting.guests.map(guest => (Object.assign(Object.assign({}, guest), { name: guest.firstName ? `${guest.firstName} ${guest.lastName}` : guest.title }))), startDate: new Date(meeting.startDate * 1000), endDate: new Date(meeting.endDate * 1000) })))
        });
      }));
    }
    else if (calendarConfigId === 'mentornity-structured-calendar-config') {
      // getting meetings in a structured program
      // the response contains all the meetings with different users
      // here we filter the events based on the user id we're viewing
      const userIdToView = new URLSearchParams(window.location.search).get('uid');
      return new Promise((async (resolve) => {
        const response = await this.client.get(`organisations/${this.context.organisationDomain}/meetingsInMeetingGoal`, { limit: 1000 });
        resolve({
          results: response.results
            .filter(meeting => meeting.guests.some(guest => guest._id === userIdToView))
            .map(meeting => (Object.assign(Object.assign({}, meeting), { meetingType: meeting.meetingGoalIdentifier, startDate: new Date(meeting.startDate * 1000), endDate: new Date(meeting.endDate * 1000) })))
        });
      }));
    }
    return Promise.reject('unexpected-calendar-config');
  }
  getUnavailabilitiesOfUser(_calendarConfigId, userId, _startTime, _endTime) {
    const { role, userId: userIdInContext, groupId } = this.context;
    const isGroupedProgram = this.organisationConfig.menteeType === 'group';
    const isMentorGettingOwnData = role === 'mentor' && userId === userIdInContext;
    const isMentorGettingAnotherGuestData = role === 'mentor' && userId !== userIdInContext;
    const isMenteeGettingOwnData = role === 'mentee' && userId === userIdInContext;
    const isMenteeGettingAnotherGuestData = role === 'mentee' && userId !== userIdInContext;
    let roleToCheck = 'mentors';
    if (isMentorGettingOwnData || isMenteeGettingAnotherGuestData) {
      roleToCheck = 'mentors';
    }
    else if (isMenteeGettingOwnData || isMentorGettingAnotherGuestData) {
      roleToCheck = isGroupedProgram ? 'groups' : 'mentees';
    }
    let idToCheck = userId;
    if (isMenteeGettingOwnData && isGroupedProgram) {
      // mentee is getting its group unavailabilities
      idToCheck = groupId;
    }
    return new Promise((resolve => {
      this.client.get(`organisations/${this.context.organisationId}/${roleToCheck}/${idToCheck}/unavailabilities`).then(response => {
        resolve({
          results: response.results,
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  createMeeting(meeting) {
    const mentornityEvent = convertDevingenEventToMentornityEvent(this.context, this.organisationConfig, meeting);
    return new Promise(((resolve, reject) => {
      this.client.post('events', mentornityEvent).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
}
