import { r as registerInstance, h } from './index-ecdfb761.js';
import { c as convertValues } from './action-util-f72a13be.js';
import { g as generateFieldModelFromRawData } from './FieldModelGenerator-378c8613.js';
import { S as SingleChoiceField } from './index-23baeeef.js';
import { f as findField } from './field-5a687ea4.js';
import { S as SozlukApi } from './index-3bf9b308.js';
import './apiBase-6015f41f.js';
import './data-transfer-field-2f305919.js';
import './filter-cbaa3d7d.js';
import { g as getSessionDetails, c as createMentornityApiInstance, m as mentornityApiEndpoint } from './session-2a491341.js';
import { s as sozlukEntries, d as MentornityAnnouncementWrapperI18nKey, e as mentornityAnnouncementWrapperI18nDefault } from './sozluk-entries-1e8f5234.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 { b as convertMentornityFieldToDevingenField } from './mentorinty-bridge-api-5ca2d652.js';
import { c as convertFieldsToFieldReferences } from './common-wrapper-util-e4afa19b.js';
import './reference-field-a5b414d1.js';
import './BaseField-0b01dc2c.js';
import './index-61dcd269.js';
import './FieldGenerator-3ae403b2.js';
import './date-1bc489bd.js';
import './index-4e451db4.js';
import './index-09efdc01.js';
import './index-150b6a59.js';
import './membership-b6639471.js';
import './data-model-88af49fc.js';
import './string-3065a411.js';
import './User-72c4643a.js';
import './UserSettings-7e4170a7.js';
import './cookie-5d9f5819.js';
import './kimlik-api-fddeac81.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './calendar-470c802a.js';
import './index-a3ca021c.js';
import './moment-65eca6b3.js';
import './i18n-09a07b97.js';
import './i18n-0e757ca5.js';
import './index-e66e8eca.js';
import './attachment-961dd228.js';
import './CalendarConfig-412d1b0f.js';

class UpdateUserMetadataHandler {
  constructor(userMetadata) {
    this.userMetadata = userMetadata;
    const { headers } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
  }
  onSubmit(event) {
    const { values } = event.detail;
    const metadataData = values;
    return new Promise((resolve, reject) => {
      let promises = [];
      if (this.userMetadata) {
        promises.push(this.api.update('metadatas', this.userMetadata._id, {
          data: Object.assign(Object.assign({}, this.userMetadata.data), metadataData)
        }));
      }
      Promise.all(promises)
        .then(() => resolve({}))
        .catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

function getFormParameters(mentornityCookieContext, config, userMetadata) {
  const data = {};
  const { role } = mentornityCookieContext;
  const metadataFields = ((role === 'mentor' ? config.metadatas.mentor : config.metadatas.mentee) || [])
    .map(convertMentornityFieldToDevingenField);
  metadataFields.forEach((field) => {
    data[field.id] = userMetadata.data[field.id];
  });
  return data;
}
function getFormViewConfig(mentornityCookieContext, config, userMetadata) {
  if (!config) {
    return null;
  }
  const { role } = mentornityCookieContext;
  const fieldsDefinitionForTable = getMetadataFormFields(role, config);
  const fieldReferencesForForm = convertFieldsToFieldReferences(fieldsDefinitionForTable);
  return FormViewConfig.decode({
    _id: 'update-user-metadata-form',
    base: 'mentornity',
    table: TableConfig.decode({
      name: 'mentees',
      fields: fieldsDefinitionForTable,
    }),
    type: AppViewType.FormView,
    handler: new UpdateUserMetadataHandler(userMetadata),
    ui: {
      fields: fieldReferencesForForm
    }
  });
}
function getMetadataFormFields(role, config) {
  let metadataFields = [];
  metadataFields = ((role === 'mentor' ? config.metadatas.mentor : config.metadatas.mentee) || [])
    .map(convertMentornityFieldToDevingenField);
  const fieldsDefinitionForTable = [...metadataFields];
  return fieldsDefinitionForTable;
}

function getFieldFromFormFieldConfig(fields, fieldData) {
  return fieldData.field || findField(fields, fieldData.fieldId);
}
// sets value if the parameters contain value for fields
const prepareFields = (view, params = {}) => {
  const data = convertValues(view.conversionConfig, params);
  return view.ui.fields.map(formFieldConfig => {
    var _a;
    const field = generateFieldModelFromRawData(getFieldFromFormFieldConfig(view.table.fields, formFieldConfig));
    const value = data[field.id];
    if (value && field.type === SingleChoiceField.type) {
      const singleChoice = field;
      if (singleChoice.dataProvider) {
        // dvn-select doesn't show any data if it has a data provider (meaning that the options are not set)
        // we need to pass initial options with the selected value in it
        singleChoice.dataProvider.setInitialData([value]);
      }
      field.setValue(((_a = singleChoice.dataAdapter) === null || _a === void 0 ? void 0 : _a.value(value)) || value);
    }
    else if (value) {
      field.setValue(value);
    }
    return field;
  });
};
const MentornityUserMetadataForm = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.isFetching = false;
    this.isProgressing = false;
    this.setDictionary = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      // using common strings of announcement dictionary
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
    this.onSubmit = (event, view) => {
      if (!view.handler.onSubmit) {
        return;
      }
      this.isProgressing = true;
      this.formErrors = undefined;
      view.handler.onSubmit(event).then(() => {
        this.isProgressing = false;
        window.dispatchEvent(new CustomEvent('dvn.mentornity-user-metadata-form.go-next-step'));
      }).catch(errors => {
        this.isProgressing = false;
        this.formErrors = errors;
      });
    };
  }
  componentWillLoad() {
    const { context: { organisationId, role, userId }, headers } = getSessionDetails();
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId).then((response) => {
      this.organisationConfig = response;
    });
    this.setDictionary();
    this.isFetching = true;
    mentornityApi.getMetadataOfUser(organisationId, role === 'mentor' ? 'mentors' : 'mentees', userId)
      .then(response => {
      this.userMetadata = response;
    });
    this.isFetching = false;
  }
  render() {
    var _a, _b;
    if (this.isFetching || !this.userMetadata || !this.organisationConfig || !this.strings) {
      return (h("mentornity-root-wrapper", null, h("div", { class: "d-flex justify-content-center pt-3" }, h("dvn-progress", { indefinite: true }))));
    }
    const { context } = getSessionDetails();
    const params = getFormParameters(context, this.organisationConfig, this.userMetadata);
    const view = getFormViewConfig(context, this.organisationConfig, this.userMetadata);
    const hasMetadata = ((_b = (_a = view.table) === null || _a === void 0 ? void 0 : _a.fields) === null || _b === void 0 ? void 0 : _b.length) > 0;
    return (h("mentornity-root-wrapper", null, !hasMetadata &&
      h("p", null, this.strings.noMetadataFound), h("doldurma-form", { fields: prepareFields(view, params), onSubmit: (event) => this.onSubmit(event, view), submitButtonLabel: hasMetadata ? `${this.strings.save} & ${this.strings.next}` : this.strings.next, progressing: this.isProgressing, formErrors: this.formErrors })));
  }
};

export { MentornityUserMetadataForm as mentornity_user_metadata_form };
