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 { 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 { MembershipConfig } from '@dvn/core/models/membership-config';
import { User } from '@dvn/kimlik/api/models';
import skills from '../constants/skills';
import skillsEN from '../constants/skills-en';
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 commonUserInfoFields = [
  generateFieldModelFromRawData({ id: 'fullName', 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: 'multipleChoice',
    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', 'fullName', 'imageUrl', 'users', [
    new AttachmentField('imageUrl', ''),
    new TextField('firstName', 'First Name'),
    new TextField('lastName', 'Last Name'),
    new TextField('fullName', 'Last Name'),
  ], false),
];
export function convertMentornityFieldToDevingenField(field) {
  if (field.type === 'ratingStars') {
    return new RangeField(field.id, field.title, field.description, 0.2, 0.2, 1).setInputType('stars');
  }
  else if (field.type === 'singleChoice') {
    return new SingleChoiceField(field.id, field.title, field.options, field.description, field.inputType, field.placeholder);
  }
  return generateFieldModelFromRawData(field);
}
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), { fullName: `${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 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({ fullName: `${response.firstName} ${response.lastName}`, user: User.decode(rest) }, (((_a = response.metadata) === null || _a === void 0 ? void 0 : _a.data) || {})), { title, bio, skills }))
            ]
          });
        }).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 => item.subscription.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) || {})), { fullName: `${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) || {})), { fullName: `${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 => !!item.subscription.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 => !!item.subscription.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, _collection, _structureId, _userRefFieldValue) {
    // 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(`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: string): Promise<MembershipConfig> {
  //   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({
          roleName,
          fields,
        }));
      }).catch(_e => {
        // console.log(e);
      });
    }));
  }
  updateMembership(_membershipConfigId, _membershipId, _data) {
    // console.log('MBA.updateMembership', id, data);
    return Promise.reject({ status: 418 });
  }
}
