'use strict';

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

const index$1 = require('./index-7cdf1df1.js');
const index = require('./index-c2a077ae.js');
require('./InterceptorHandler-09a1e84b.js');
require('./state-tunnel-786a62ce.js');
require('./data-model-f9df493f.js');
require('./BaseField-f50bb8f0.js');
const FieldModelGenerator = require('./FieldModelGenerator-5a321a60.js');
require('./date-8e8ca89a.js');
require('./index-e79eb186.js');
const tableConfig = require('./table-config-b20b4da1.js');
require('./string-9e6ebf63.js');
require('./membership-config-47f4733e.js');
require('./User-ed078a17.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-13fb62eb.js');
const index$2 = require('./index-3f86c4f4.js');
const models = require('./models-813707d2.js');
require('./kimlikApi-6a581864.js');
require('./data-transfer-field-025bce2f.js');
require('./filter-52876f3c.js');
require('./cookie-8a49bf23.js');
const ValidatorLength = require('./ValidatorLength-06e5c6f8.js');
const formViewConfig = require('./form-view-config-cc5244bd.js');
const viewConfig = require('./view-config-f8b4b929.js');
const actions = require('./actions-d7eabd95.js');
require('./attachment-c2bc9126.js');
const instance = require('./instance-adc7fc02.js');
const session = require('./session-a266bfc2.js');
require('./index-35a4d634.js');
const commonWrapperUtil = require('./common-wrapper-util-89cc9c36.js');

const en = {
  formView: {
    fetchError: 'Fetching data failed.',
    retry: 'Retry',
    submit: 'Update Info',
  },
  formFields: {
    bio: 'Bio',
    firstName: 'First name',
    lastName: 'Last name',
    pairLimit: 'Pair limit',
    skills: 'Professional Expertise',
    title: 'Title',
  }
};
const tr = {
  formView: {
    fetchError: 'Veri alırken hata oluştu.',
    retry: 'Tekrar Dene',
    submit: 'Bilgileri Güncelle',
  },
  formFields: {
    bio: 'Kısaca kendinizi tanıtın',
    firstName: 'İsim',
    lastName: 'Soyisim',
    pairLimit: 'Eşleşme sınırı',
    skills: 'Uzmanlık Alanlarınız',
    title: 'Ünvan',
  }
};

var __rest = (undefined && undefined.__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;
};
class UpdateMembershipInfoFormHandler {
  constructor(user, userMetadata, userMentorship) {
    this.user = user;
    this.userMetadata = userMetadata;
    this.userMentorship = userMentorship;
    const { headers } = session.getSessionDetails();
    this.api = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
  }
  onSubmit(event) {
    const { values } = event.detail;
    const { firstName, lastName, bio, skills, title, subscriptionLimit } = values, rest = __rest(values, ["firstName", "lastName", "bio", "skills", "title", "subscriptionLimit"]);
    const profileData = {
      firstName, lastName, bio, skills, title,
    };
    const mentorshipData = { subscriptionLimit: parseInt(subscriptionLimit) };
    const metadataData = rest;
    return new Promise((resolve, reject) => {
      let promises = [
        this.api.update('users', this.user._id, profileData),
      ];
      if (this.userMetadata) {
        promises.push(this.api.update('metadatas', this.userMetadata._id, { data: metadataData }));
      }
      if (this.userMentorship) {
        promises.push(this.api.update('mentorships', this.userMentorship._id, mentorshipData));
      }
      Promise.all(promises).then(() => resolve({
        events: [
          new actions.NotificationAction(models.Notification.congratulate('Info updated')),
        ],
      }))
        .catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

function getFormParameters(mentornityCookieContext, config, user, userMetadata, userMentorship) {
  const data = {
    firstName: user.firstName,
    lastName: user.lastName,
    bio: user.bio,
    title: user.title,
    skills: user.skills,
  };
  const { role } = mentornityCookieContext;
  const canEditMetadata = role === 'mentor'
    ? config.metadatas.mentorsCanEditMetadata
    : config.metadatas.menteesCanEditMetadata;
  if (canEditMetadata) {
    const metadataFields = ((role === 'mentor' ? config.metadatas.mentor : config.metadatas.mentee) || [])
      .map(commonWrapperUtil.convertMentornityFieldToDevingenField);
    metadataFields.forEach((field) => {
      data[field.id] = userMetadata.data[field.id];
    });
  }
  if (userMentorship) {
    data.subscriptionLimit = userMentorship.subscriptionLimit;
  }
  return data;
}
function getFormViewConfig(mentornityCookieContext, language, config, user, userMetadata, userMentorship) {
  var _a, _b;
  if (!config) {
    return null;
  }
  const i18n = language === 'tr' ? tr : en;
  const { role } = mentornityCookieContext;
  const profileFieldVisibility = role === 'mentor'
    ? config.profileFieldVisibilities.mentor
    : config.profileFieldVisibilities.mentee;
  const defaultUserFields = [
    new index.TextField('firstName', i18n.formFields.firstName)
      .addInterceptor('onSubmit', new ValidatorLength.ValidatorLength(2, 32))
      .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer())
      .require(),
    new index.TextField('lastName', i18n.formFields.lastName)
      .addInterceptor('onSubmit', new ValidatorLength.ValidatorLength(2, 32))
      .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer())
      .require(),
    ...[
      new index.TextField('title', i18n.formFields.title)
        .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer()),
      new index.TextField('bio', i18n.formFields.bio)
        .setLines(3)
        .setLinesMax(10),
      FieldModelGenerator.generateFieldModelFromRawData({
        id: 'skills',
        title: i18n.formFields.skills,
        type: 'multipleChoice',
        inputType: 'select',
        options: commonWrapperUtil.skills.map(skill => ({
          label: commonWrapperUtil.skillsEN[skill], value: skill,
        })),
      }),
    ].filter(field => profileFieldVisibility[field.id]),
  ];
  const canEditMetadata = role === 'mentor'
    ? config.metadatas.mentorsCanEditMetadata
    : config.metadatas.menteesCanEditMetadata;
  let metadataFields = [];
  if (canEditMetadata) {
    metadataFields = ((role === 'mentor' ? config.metadatas.mentor : config.metadatas.mentee) || [])
      .map(commonWrapperUtil.convertMentornityFieldToDevingenField);
  }
  const canMentorEditSubscriptionLimit = (_b = (_a = config.welcomeStepVisibilities) === null || _a === void 0 ? void 0 : _a.mentor) === null || _b === void 0 ? void 0 : _b.mentorshipLimit;
  const fieldsDefinitionForTable = (role === 'mentor' && canMentorEditSubscriptionLimit)
    ? [...defaultUserFields, new FieldModelGenerator.NumberField('subscriptionLimit', i18n.formFields.pairLimit), ...metadataFields]
    : [...defaultUserFields, ...metadataFields];
  const fieldReferencesForForm = commonWrapperUtil.convertFieldsToFieldReferences(fieldsDefinitionForTable);
  return formViewConfig.FormViewConfig.decode({
    _id: 'update-membership-info-page',
    base: 'mentornity',
    title: 'My info',
    table: tableConfig.TableConfig.decode({
      name: 'mentees',
      fields: fieldsDefinitionForTable,
    }),
    type: viewConfig.AppViewType.FormView,
    handler: new UpdateMembershipInfoFormHandler(user, canEditMetadata ? userMetadata : undefined, userMentorship),
    ui: {
      fields: fieldReferencesForForm,
      i18n: i18n.formView,
    }
  });
}

const MentornityMembershipSettingsWrapper = class {
  constructor(hostRef) {
    index$1.registerInstance(this, hostRef);
  }
  onInvalidation(event) {
    this.notifier.showCustomNotification(event.detail.notification);
  }
  ;
  componentWillLoad() {
    const { context, headers } = session.getSessionDetails();
    const mentornityApi = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(context.organisationId).then((response) => {
      this.organisationConfig = response;
    });
    mentornityApi.get('users', context.userId).then((response) => {
      this.user = response;
    });
    mentornityApi
      .getMetadataOfUser(context.organisationId, session.getSessionDetails().context.role === 'mentor' ? 'mentors' : 'mentees', context.userId)
      .then((response) => {
      this.userMetadata = response;
    });
    if (session.getSessionDetails().context.role === 'mentor') {
      mentornityApi
        .getMentorshipOfUser(context.organisationId, context.userId)
        .then((response) => {
        this.userMentorship = response;
      });
    }
  }
  render() {
    const { language, organisationConfig, user, userMentorship, userMetadata } = this;
    const { context } = session.getSessionDetails();
    if (!organisationConfig || !user || !userMetadata || (context.role === 'mentor' && !userMentorship)) {
      return (index$1.h("mentornity-root-wrapper", null, index$1.h("div", { class: "d-flex justify-content-center pt-3" }, index$1.h("dvn-progress", { indefinite: true }))));
    }
    const pairDetailViewConfig = getFormViewConfig(context, language, organisationConfig, user, userMetadata, userMentorship);
    return (index$1.h("mentornity-root-wrapper", null, index$1.h("dvn-card", null, index$1.h("dvn-app-view-form-view", { params: getFormParameters(context, organisationConfig, user, userMetadata, userMentorship), view: pairDetailViewConfig }))));
  }
};
index$2.injectNotifier(MentornityMembershipSettingsWrapper);

exports.mentornity_membership_settings_wrapper = MentornityMembershipSettingsWrapper;
