'use strict';

const FieldModelGenerator = require('./FieldModelGenerator-1af8e5c3.js');
const index$1 = require('./index-93271b8c.js');
const index = require('./index-7e3bc620.js');
const ModifierTrimmer = require('./ModifierTrimmer-1463d100.js');
const ValidatorLength = require('./ValidatorLength-06e5c6f8.js');
const formViewConfig = require('./form-view-config-b408970d.js');
const tableConfig = require('./table-config-73a193be.js');
const viewConfig = require('./view-config-1c8cc7cb.js');
const instance = require('./instance-fba77445.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-616ff4b9.js');
const commonWrapperUtil = require('./common-wrapper-util-f504304b.js');
const models = require('./models-813707d2.js');
const actions = require('./actions-d7eabd95.js');
require('./apiBase-b14a8285.js');
require('./data-transfer-field-0ce05c1a.js');
require('./filter-d5040f65.js');
const env = require('./env-56a21d68.js');
const session = require('./session-fe19e012.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(env.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 && subscriptionLimit !== undefined) {
        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(mentorintyBridgeApi.convertMentornityFieldToDevingenField);
    metadataFields.forEach((field) => {
      data[field.id] = userMetadata.data[field.id];
    });
  }
  if (userMentorship) {
    data.subscriptionLimit = userMentorship.subscriptionLimit;
  }
  return data;
}
function getFormViewConfig(mentornityCookieContext, language, config, viewConfigWrapper, user, userMetadata, userMentorship) {
  var _a;
  if (!config) {
    return null;
  }
  const i18n = language === 'tr' ? tr : en;
  const { role } = mentornityCookieContext;
  const fieldsDefinitionForTable = getAvailableMembershipFormFields(i18n, role, config);
  const fieldReferencesForForm = ((_a = viewConfigWrapper === null || viewConfigWrapper === void 0 ? void 0 : viewConfigWrapper.dvnAppViewConfig) === null || _a === void 0 ? void 0 : _a.ui.fields)
    || commonWrapperUtil.convertFieldsToFieldReferences(fieldsDefinitionForTable);
  const canEditMetadata = role === 'mentor'
    ? config.metadatas.mentorsCanEditMetadata
    : config.metadatas.menteesCanEditMetadata;
  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,
    }
  });
}
function getAvailableMembershipFormFields(i18n, role, config) {
  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 ModifierTrimmer.ModifierTrimmer())
      .require(),
    new index.TextField('lastName', i18n.formFields.lastName)
      .addInterceptor('onSubmit', new ValidatorLength.ValidatorLength(2, 32))
      .addInterceptor('onSubmit', new ModifierTrimmer.ModifierTrimmer())
      .require(),
    ...[
      new index.TextField('title', i18n.formFields.title)
        .addInterceptor('onSubmit', new ModifierTrimmer.ModifierTrimmer()),
      new index.TextField('bio', i18n.formFields.bio)
        .setLines(3)
        .setLinesMax(10),
      FieldModelGenerator.generateFieldModelFromRawData({
        id: 'skills',
        title: i18n.formFields.skills,
        type: 'multiple-choice',
        inputType: 'select',
        options: mentorintyBridgeApi.skills.map(skill => ({
          label: mentorintyBridgeApi.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(mentorintyBridgeApi.convertMentornityFieldToDevingenField);
  }
  const isPairedProgram = config.mentorMenteeSubscription === instance.ConfigMentorMenteeSubscription.Restricted;
  const fieldsDefinitionForTable = (role === 'mentor' && isPairedProgram)
    ? [...defaultUserFields, new index$1.NumberField('subscriptionLimit', i18n.formFields.pairLimit), ...metadataFields]
    : [...defaultUserFields, ...metadataFields];
  return fieldsDefinitionForTable;
}

exports.getAvailableMembershipFormFields = getAvailableMembershipFormFields;
exports.getFormParameters = getFormParameters;
exports.getFormViewConfig = getFormViewConfig;
