import { g as generateFieldModelFromRawData, N as NumberField } from './FieldModelGenerator-378c8613.js';
import { T as TextField } from './index-150b6a59.js';
import { M as ModifierTrimmer } from './ModifierTrimmer-2f77f917.js';
import { V as ValidatorLength } from './ValidatorLength-f56a7c14.js';
import { F as FormViewConfig } from './form-view-config-e5a5ced8.js';
import { T as TableConfig } from './table-config-d73a72ab.js';
import { A as AppViewType } from './view-config-1ed8c59f.js';
import { g as getSessionDetails, c as createMentornityApiInstance, m as mentornityApiEndpoint, i as ConfigMentorMenteeSubscription } from './session-2a491341.js';
import { b as convertMentornityFieldToDevingenField, s as skills, d as skillsEN } from './mentorinty-bridge-api-5ca2d652.js';
import { c as convertFieldsToFieldReferences } from './common-wrapper-util-e4afa19b.js';
import { a as Notification } from './models-f0bc20c6.js';
import { N as NotificationAction } from './actions-b9a0f808.js';
import './apiBase-6015f41f.js';
import './data-transfer-field-2f305919.js';
import './filter-cbaa3d7d.js';

const en = {
  formView: {
    fetchError: 'Fetching data failed.',
    retry: 'Retry',
    submit: 'Update Info',
    myInfo: 'My Info',
    infoUpdated: 'Info Updated',
  },
  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',
    myInfo: 'Bilgilerim',
    infoUpdated: 'Bilgiler Güncellendi',
  },
  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',
  }
};
const pt_br = {
  formView: {
    fetchError: 'Falha na busca de dados.',
    retry: 'Repetir',
    submit: 'Informação de atualização',
    myInfo: 'Minha informação',
    infoUpdated: 'Informações atualizadas',
  },
  formFields: {
    bio: 'Biografia',
    firstName: 'Primeiro nome',
    lastName: 'Último nome',
    pairLimit: 'Limite de pares',
    skills: 'Experiência profissional',
    title: 'Título',
  }
};

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, language) {
    this.user = user;
    this.language = language;
    this.userMetadata = userMetadata;
    this.userMentorship = userMentorship;
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(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: Object.assign(Object.assign({}, this.userMetadata.data), metadataData)
        }));
      }
      if (this.userMentorship && subscriptionLimit !== undefined) {
        promises.push(this.api.update('mentorships', this.userMentorship._id, mentorshipData));
      }
      const i18n = this.language === 'tr'
        ? tr
        : (this.language === 'pt-br' ? pt_br : en);
      Promise.all(promises).then(() => resolve({
        events: [
          new NotificationAction(Notification.congratulate(i18n.formView.infoUpdated)),
        ],
      }))
        .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(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
    : (language === 'pt-br' ? pt_br : 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)
    || convertFieldsToFieldReferences(fieldsDefinitionForTable);
  const canEditMetadata = role === 'mentor'
    ? config.metadatas.mentorsCanEditMetadata
    : config.metadatas.menteesCanEditMetadata;
  return FormViewConfig.decode({
    _id: 'update-membership-info-page',
    base: 'mentornity',
    title: i18n.formView.myInfo,
    table: TableConfig.decode({
      name: 'mentees',
      fields: fieldsDefinitionForTable,
    }),
    type: AppViewType.FormView,
    handler: new UpdateMembershipInfoFormHandler(user, canEditMetadata ? userMetadata : undefined, userMentorship, language),
    ui: {
      fields: fieldReferencesForForm,
      i18n: i18n.formView,
    }
  });
}
function getAvailableMembershipFormFields(i18n, role, config) {
  const profileFieldVisibility = role === 'mentor'
    ? config.profileFieldVisibilities.mentor
    : config.profileFieldVisibilities.mentee;
  const defaultUserFields = [
    new TextField('firstName', i18n.formFields.firstName)
      .addInterceptor('onSubmit', new ValidatorLength(2, 32))
      .addInterceptor('onSubmit', new ModifierTrimmer())
      .require(),
    new TextField('lastName', i18n.formFields.lastName)
      .addInterceptor('onSubmit', new ValidatorLength(2, 32))
      .addInterceptor('onSubmit', new ModifierTrimmer())
      .require()
  ];
  if (!config.webAppConfiguration.membershipForm) {
    defaultUserFields.push(...[
      new TextField('title', i18n.formFields.title)
        .addInterceptor('onSubmit', new ModifierTrimmer()),
      new TextField('bio', i18n.formFields.bio)
        .setLines(3)
        .setLinesMax(10),
      generateFieldModelFromRawData({
        id: 'skills',
        title: i18n.formFields.skills,
        type: 'multiple-choice',
        inputType: 'select',
        options: skills.map(skill => ({
          label: 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(convertMentornityFieldToDevingenField);
  }
  const isPairedProgram = config.mentorMenteeSubscription === ConfigMentorMenteeSubscription.Restricted;
  const fieldsDefinitionForTable = (role === 'mentor' && isPairedProgram)
    ? [...defaultUserFields, new NumberField('subscriptionLimit', i18n.formFields.pairLimit), ...metadataFields]
    : [...defaultUserFields, ...metadataFields];
  return fieldsDefinitionForTable;
}

export { getFormViewConfig as a, getFormParameters as b, getAvailableMembershipFormFields as g };
