'use strict';

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

const index = require('./index-1141a245.js');
const actionUtil = require('./action-util-7006ea09.js');
const FieldModelGenerator = require('./FieldModelGenerator-d61f01d4.js');
const index$2 = require('./index-9d3d3d15.js');
const field = require('./field-2133746c.js');
const index$1 = require('./index-a2e99c85.js');
require('./apiBase-6c66ff1b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const session = require('./session-f588baa3.js');
const sozlukEntries = require('./sozluk-entries-3b9686e7.js');
const formViewConfig = require('./form-view-config-a2d48c27.js');
const tableConfig = require('./table-config-969d3038.js');
const viewConfig = require('./view-config-52c16db0.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-b1eaa56d.js');
const commonWrapperUtil = require('./common-wrapper-util-95591ac2.js');
require('./reference-field-1239b0c3.js');
require('./BaseField-381327a9.js');
require('./index-2eea69a0.js');
require('./FieldGenerator-279a646b.js');
require('./date-a24d7714.js');
require('./index-0783d14f.js');
require('./index-9fd84b93.js');
require('./index-61f9621a.js');
require('./membership-e87e02ed.js');
require('./data-model-01c368bc.js');
require('./string-de672b69.js');
require('./User-dbfbd45e.js');
require('./UserSettings-2a2399b1.js');
require('./cookie-e64bc800.js');
require('./kimlik-api-663f4884.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./calendar-e4b7baeb.js');
require('./index-b776fc14.js');
require('./moment-7a3433f2.js');
require('./i18n-0bcf144d.js');
require('./i18n-77d45414.js');
require('./index-b7855ed6.js');
require('./attachment-a0cdf203.js');
require('./CalendarConfig-998f742e.js');

class UpdateUserMetadataHandler {
  constructor(userMetadata) {
    this.userMetadata = userMetadata;
    const { headers } = session.getSessionDetails();
    this.api = session.createMentornityApiInstance(session.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(mentorintyBridgeApi.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 = commonWrapperUtil.convertFieldsToFieldReferences(fieldsDefinitionForTable);
  return formViewConfig.FormViewConfig.decode({
    _id: 'update-user-metadata-form',
    base: 'mentornity',
    table: tableConfig.TableConfig.decode({
      name: 'mentees',
      fields: fieldsDefinitionForTable,
    }),
    type: viewConfig.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(mentorintyBridgeApi.convertMentornityFieldToDevingenField);
  const fieldsDefinitionForTable = [...metadataFields];
  return fieldsDefinitionForTable;
}

function getFieldFromFormFieldConfig(fields, fieldData) {
  return fieldData.field || field.findField(fields, fieldData.fieldId);
}
// sets value if the parameters contain value for fields
const prepareFields = (view, params = {}) => {
  const data = actionUtil.convertValues(view.conversionConfig, params);
  return view.ui.fields.map(formFieldConfig => {
    var _a;
    const field = FieldModelGenerator.generateFieldModelFromRawData(getFieldFromFormFieldConfig(view.table.fields, formFieldConfig));
    const value = data[field.id];
    if (value && field.type === index$2.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) {
    index.registerInstance(this, hostRef);
    this.isFetching = false;
    this.isProgressing = false;
    this.setDictionary = async () => {
      const apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
      // using common strings of announcement dictionary
      this.strings = await apiSozluk.getContent(sozlukEntries.MentornityAnnouncementWrapperI18nKey, sozlukEntries.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 } = session.getSessionDetails();
    const mentornityApi = session.createMentornityApiInstance(session.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 (index.h("mentornity-root-wrapper", null, index.h("div", { class: "d-flex justify-content-center pt-3" }, index.h("dvn-progress", { indefinite: true }))));
    }
    const { context } = session.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 (index.h("mentornity-root-wrapper", null, !hasMetadata &&
      index.h("p", null, this.strings.noMetadataFound), index.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 })));
  }
};

exports.mentornity_user_metadata_form = MentornityUserMetadataForm;
