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';
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',
    showMore: 'Show more',
    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',
    showMore: 'Mostre mais',
    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',
    showMore: '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 convertDevingenAvailabilityToMentornityAvailability(context, mentorship, availability) {
  return {
    status: 'active',
    // slotCount: state.count,
    endDate: new Date(availability.endDate).getTime() / 1000,
    startDate: new Date(availability.startDate).getTime() / 1000,
    meetingDuration: availability.meetingDuration,
    meetingBreaks: availability.breakDuration,
    location: {
      address: availability.location,
      type: availability.locationType,
    },
    createdBy: {
      _type: 'reference',
      _class: 'users',
      _id: context.userId,
    },
    mentorship: {
      _type: 'reference',
      _class: 'mentorships',
      _id: mentorship._id,
    },
    owner: {
      _type: 'reference',
      _class: 'users',
      _id: availability.user._id,
    },
    organisation: {
      _type: 'reference',
      _class: 'organisations',
      _id: context.organisationId,
    },
    recurrence: availability.recurrence,
  };
}
function convertDevingenEventToMentornityEvent(context, organisationConfig, event) {
  var _a, _b, _c;
  const { organisationId, userId, role } = context;
  let guests = [];
  if (event.guestMetadata) {
    // roles are in the guest metadata
    guests = event.guests.map((guest, i) => {
      const collection = event.guestMetadata[i].membershipConfigId;
      return {
        _id: guest._id,
        _class: collection === 'groups' ? 'groups' : 'users',
        _type: 'reference'
      };
    });
  }
  else if (organisationConfig.menteeType === 'group') {
    // TODO remove this part. all meetings should contain guestMetadata and fall into the previous block
    const currentUserAsGuest = event.guests.find(guest => guest._id === userId);
    const otherGuest = event.guests.find(guest => guest._id !== userId);
    // 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 guestsOrdered = role === 'mentor' ? [currentUserAsGuest, otherGuest] : [otherGuest, currentUserAsGuest];
    guests = guestsOrdered.map(guest => ({
      _id: guest._id,
      _class: guest._ref === 'kimlik-users' ? 'users' : guest._ref,
      _type: 'reference'
    }));
  }
  const meeting = {
    location: (((_a = event.locations) === null || _a === void 0 ? void 0 : _a[0]) || {}),
    // createdBy: convertDevingenRefToMentornityRef(event.createdBy),
    organisation: {
      _id: organisationId,
      _class: 'organisations',
      _type: 'reference'
    },
    guests,
    type: 'meeting',
    status: 'active',
    startDate: new Date(event.startDate).getTime() / 1000,
    endDate: new Date(event.endDate).getTime() / 1000,
  };
  if ((_b = event.availability) === null || _b === void 0 ? void 0 : _b._id) {
    meeting.availability = {
      _id: (_c = event.availability) === null || _c === void 0 ? void 0 : _c._id,
      _class: 'availabilities',
      _type: 'reference'
    };
  }
  if (event.meetingType) {
    meeting.meetingGoalIdentifier = event.meetingType;
  }
  return meeting;
}
function convertMentornityEventToDevingenEvent(event) {
  return Object.assign(Object.assign({}, event), { startDate: new Date(event.startDate * 1000).toISOString(), endDate: new Date(event.endDate * 1000).toISOString(), guests: event.guests.map(guest => (Object.assign(Object.assign({}, guest), { name: guest.firstName ? `${guest.firstName} ${guest.lastName}` : guest.title, initials: guest.firstName ? `${guest.firstName[0]} ${guest.lastName[0]}` : guest.title[0] }))), guestMetadata: event.guests.map((_, i) => {
      if (i === 0) {
        return {
          membershipConfigId: 'mentors',
        };
      }
      return {
        // membershipConfigId: 'mentees',
        membershipConfigId: 'groups',
      };
    }) });
}
function convertUserListToMembershipList(response, membershipConfigId) {
  var _a;
  // separate metadata and user data. consider title, bio and skills as metadata
  return {
    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, subscription, mentorship } = 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, 
        // membership config reference in the membership
        config: { _id: membershipConfigId }, 
        // used on mentor list to follow/unfollow users
        subscription,
        // used on mentor list to follow/unfollow users
        mentorship }));
    }).sort((a, b) => a.user.name.localeCompare(b.user.name))
  };
}
function convertGroupListToMembershipList(response) {
  var _a;
  // separate metadata and user data. consider title, bio and skills as metadata
  return {
    meta: {
      total: ((_a = response.meta) === null || _a === void 0 ? void 0 : _a.total) || 0,
    },
    results: response.results.map((group) => {
      const { _id, title } = group;
      // auto generated values. used in cardViewConfig
      const name = title;
      const initials = title[0];
      return Membership.decode({
        // user id is used as membership id too
        _id,
        // user data
        user: { _id, name, initials },
      });
    }).sort((a, b) => a.user.name.localeCompare(b.user.name))
  };
}
export function generateCalendarConfig(config) {
  const { meetingSettings } = config;
  const canMenteesCreateMeeting = !!meetingSettings.menteesCanCreateMeeting;
  const canMentorsCreateMeeting = !!meetingSettings.mentorsCanCreateMeeting;
  if (config.menteeType === 'group') {
    return CalendarConfig.decode({
      _id: 'mentornity-calendar-config',
      guestDefinitions: [{ tableId: 'mentors' }, { tableId: 'groups' }],
      permissions: [
        { membershipConfigId: 'mentors', canPickCustomTime: canMentorsCreateMeeting },
        { membershipConfigId: 'groups', canPickCustomTime: canMenteesCreateMeeting },
        { membershipConfigId: 'admins', canPickCustomTime: true }
      ],
    });
  }
  return CalendarConfig.decode({
    _id: 'mentornity-calendar-config',
    guestDefinitions: [{ tableId: 'mentors' }, { tableId: 'mentees' }],
    permissions: [
      { membershipConfigId: 'mentors', canPickCustomTime: canMentorsCreateMeeting },
      { membershipConfigId: 'mentees', canPickCustomTime: canMenteesCreateMeeting },
      { membershipConfigId: 'admins', canPickCustomTime: true }
    ],
  });
}
const membershipConfigMentor = MembershipConfig.decode({ _id: 'mentors', roleName: 'mentor' });
const membershipConfigMentee = MembershipConfig.decode({ _id: 'mentees', roleName: 'mentee' });
const membershipConfigGroup = MembershipConfig.decode({ _id: 'groups', roleName: 'group' });
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);
    if (collection === 'data-configs') {
      // this request is for getting the data configuration. return the proper data configuration
      if (id === 'mentors') {
        return Promise.resolve(membershipConfigMentor);
      }
      else if (id === 'mentees') {
        return Promise.resolve(membershipConfigMentee);
      }
      else if (id === 'groups') {
        return Promise.resolve(membershipConfigGroup);
      }
    }
    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) {
    var _a, _b, _c, _d, _f, _g, _h;
    const { organisationId } = this.context;
    if (collection === 'groups') {
      const search = (_c = (_b = (_a = query === null || query === void 0 ? void 0 : query.filter) === null || _a === void 0 ? void 0 : _a.filters) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.value;
      return new Promise((resolve => {
        this.client.get(`organisations/${organisationId}/${collection}`, { title: search, limit: 1000 }).then(response => resolve(convertGroupListToMembershipList(response)))
          .catch(e => console.log(e));
      }));
    }
    if (['mentees', 'mentors'].includes(collection)) {
      const menteeId = (_d = query === null || query === void 0 ? void 0 : query.filter) === null || _d === void 0 ? void 0 : _d.value;
      if (menteeId) {
        // 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
        // and also on the user detail page wrapper
        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(Object.assign({ user: Object.assign(Object.assign({}, rest), { initials: `${response.firstName[0]} ${response.lastName[0]}`, name: `${response.firstName} ${response.lastName}` }) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills }), rest), { 
                  // membership config reference in the membership
                  config: { _id: collection } }))
              ]
            });
          }).catch(e => {
            console.log(e);
          });
        }));
      }
      else {
        const search = (_h = (_g = (_f = query === null || query === void 0 ? void 0 : query.filter) === null || _f === void 0 ? void 0 : _f.filters) === null || _g === void 0 ? void 0 : _g[0]) === null || _h === void 0 ? void 0 : _h.value;
        return new Promise((resolve => {
          this.client.get(`organisations/${organisationId}/${collection}`, { search }).then(response => resolve(convertUserListToMembershipList(response, collection)))
            .catch(e => console.log(e));
        }));
      }
    }
    else if (['mentee-card-list', 'mentor-card-list'].includes(collection)) {
      const membershipConfigId = collection === 'mentor-card-list' ? 'mentors' : 'mentees';
      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 => resolve(convertUserListToMembershipList(response, membershipConfigId)))
          .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}`, initials: `${item.firstName[0]} ${item.lastName[0]}` }));
        })
      })).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) {
    var _a, _b;
    // 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: ((_b = (_a = this.organisationConfig) === null || _a === void 0 ? void 0 : _a.subscriptionConfig) === null || _b === void 0 ? void 0 : _b.processStartType) === 'startOnSelection'
        ? 'active'
        : '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: string): Promise<GetListResponse<Availability>> {
  //   return Promise.reject({ status: 418 });
  // }
  getAvailabilitiesOfUser(userId) {
    const { organisationId, role } = this.context;
    if (role === 'mentor' && userId !== this.context.userId) {
      // 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));
  }
  getMeetingsForCalendar(_calendarConfigId, startDate, endDate) {
    return new Promise((async (resolve) => {
      const response = await this.client.get(`organisations/${this.context.organisationDomain}/meetings`, { startDate, endDate, sort: 'startDate', status: 'active' });
      resolve({
        results: response.results.map(convertMentornityEventToDevingenEvent),
      });
    }));
  }
  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 response = await this.client.get(`${collectionToUse}/${idToUse}/events`, { organisationId: organisationId, limit: 1000 });
        let results = response.results.filter(meeting => meeting.status === 'active');
        if (guestIDs.length > 1) {
          // TODO this should be done in api
          // user is viewing the meetings with another user
          const userIdToView = guestIDs.filter(id => id !== idToUse)[0];
          results = results.filter(meeting => meeting.guests.some(guest => guest._id === userIdToView));
        }
        results = results.map(convertMentornityEventToDevingenEvent);
        resolve({ results });
      }));
    }
    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);
    // console.log(meeting);
    // console.log(mentornityEvent);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.post('events', mentornityEvent).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  createAvailability(availability) {
    const mentornityAvailability = convertDevingenAvailabilityToMentornityAvailability(this.context, this.mentorship, availability);
    // console.log(availability);
    // console.log(mentornityAvailability);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.post('availabilities', mentornityAvailability).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  updateAvailability(availability) {
    const mentornityAvailability = convertDevingenAvailabilityToMentornityAvailability(this.context, this.mentorship, availability);
    // console.log(availability);
    // console.log(mentornityAvailability);
    // return Promise.resolve({
    //   _id: 'fake',
    //   createdAt: 0,
    //   updatedAt: 0,
    // });
    return new Promise(((resolve, reject) => {
      this.client.put(`availabilities/${availability._id}`, mentornityAvailability).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
  deleteAvailability(id) {
    return new Promise(((resolve, reject) => {
      this.client.post(`availabilities/${id}/cancel`, {}).then(response => {
        resolve(response);
      }).catch(e => {
        reject(e);
      });
    }));
  }
}
