import { r as registerInstance, h } from './index-acdc1ac0.js';
import { T as TextField } from './index-d9d18e9c.js';
import './InterceptorHandler-6474bcf4.js';
import './state-tunnel-04c0b67a.js';
import './data-model-bb5789f5.js';
import './BaseField-d94c5b14.js';
import { g as generateFieldModelFromRawData, N as NumberField } from './FieldModelGenerator-755e3a85.js';
import './date-b270be76.js';
import './index-a95fa2f4.js';
import { T as TableConfig } from './table-config-9f3dee34.js';
import './string-2d991277.js';
import './membership-config-1607e716.js';
import './User-e14f1ece.js';
import './_commonjsHelpers-63c253cd.js';
import './index-fd2b14ae.js';
import { i as injectNotifier } from './index-ea30d7ec.js';
import { a as Notification } from './models-f0bc20c6.js';
import './kimlikApi-81acfec6.js';
import './data-transfer-field-1ad95e08.js';
import './filter-cbaa3d7d.js';
import './cookie-d9098150.js';
import { V as ValidatorLength } from './ValidatorLength-f56a7c14.js';
import { M as ModifierTrimmer, F as FormViewConfig } from './form-view-config-46b99ec4.js';
import { A as AppViewType } from './view-config-2a7feb02.js';
import { N as NotificationAction } from './actions-b9a0f808.js';
import './attachment-8831acff.js';
import { c as createMentornityApiInstance } from './instance-b3864e36.js';
import { g as getSessionDetails, m as mentornityApiEndpoint } from './session-78c3c986.js';
import './index-c43f1f2e.js';
import { c as convertMentornityFieldToDevingenField, s as skills, a as skillsEN, b as convertFieldsToFieldReferences } from './common-wrapper-util-c1020679.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 } = 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: metadataData }));
      }
      if (this.userMentorship) {
        promises.push(this.api.update('mentorships', this.userMentorship._id, mentorshipData));
      }
      Promise.all(promises).then(() => resolve({
        events: [
          new NotificationAction(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(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 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(),
    ...[
      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: 'multipleChoice',
        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 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 NumberField('subscriptionLimit', i18n.formFields.pairLimit), ...metadataFields]
    : [...defaultUserFields, ...metadataFields];
  const fieldReferencesForForm = convertFieldsToFieldReferences(fieldsDefinitionForTable);
  return FormViewConfig.decode({
    _id: 'update-membership-info-page',
    base: 'mentornity',
    title: 'My info',
    table: TableConfig.decode({
      name: 'mentees',
      fields: fieldsDefinitionForTable,
    }),
    type: AppViewType.FormView,
    handler: new UpdateMembershipInfoFormHandler(user, canEditMetadata ? userMetadata : undefined, userMentorship),
    ui: {
      fields: fieldReferencesForForm,
      i18n: i18n.formView,
    }
  });
}

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

export { MentornityMembershipSettingsWrapper as mentornity_membership_settings_wrapper };
