'use strict';

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

const index = require('./index-1141a245.js');
const index$2 = require('./index-f41ad23a.js');
const FieldModelGenerator = require('./FieldModelGenerator-d61f01d4.js');
const index$1 = require('./index-61f9621a.js');
const viewConfig = require('./view-config-52c16db0.js');
require('./apiBase-6c66ff1b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const session = require('./session-f588baa3.js');
const commonWrapperUtil = require('./common-wrapper-util-95591ac2.js');
const wrapperUtil = require('./wrapper-util-e22dad7f.js');
require('./state-tunnel-786a62ce.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-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./data-model-01c368bc.js');
require('./table-config-969d3038.js');
require('./membership-e87e02ed.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('./mentorinty-bridge-api-b1eaa56d.js');
require('./index-b7855ed6.js');
require('./attachment-a0cdf203.js');
require('./CalendarConfig-998f742e.js');
require('./index-a2e99c85.js');
require('./sozluk-entries-3b9686e7.js');
require('./i18n-0bcf144d.js');
require('./i18n-77d45414.js');
require('./calendar-e4b7baeb.js');
require('./index-b776fc14.js');
require('./moment-7a3433f2.js');
require('./ModifierTrimmer-1463d100.js');
require('./InterceptorHandler-09a1e84b.js');
require('./ValidatorLength-06e5c6f8.js');
require('./form-view-config-a2d48c27.js');
require('./models-813707d2.js');
require('./actions-d7eabd95.js');

class PreviewFormHandler {
  constructor(callback) {
    this.callback = callback;
  }
  onSubmit() {
    var _a;
    (_a = this.callback) === null || _a === void 0 ? void 0 : _a.call(this);
    return Promise.resolve({});
  }
}

const mentornityMembershipInfoSettingsWrapperCss = "mentornity-membership-info-settings-wrapper{display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;overflow:hidden;height:100%}mentornity-membership-info-settings-wrapper .columns-container{height:100%}mentornity-membership-info-settings-wrapper .columns-container .controls-container{-ms-flex:3;flex:3}mentornity-membership-info-settings-wrapper .columns-container .controls-container .form-controls-container{background:var(--color-elevated-item-background);-ms-flex:1;flex:1;overflow:auto}mentornity-membership-info-settings-wrapper .columns-container .controls-container .controls-footer{background:var(--color-background-secondary);text-align:right}mentornity-membership-info-settings-wrapper .columns-container .controls-container .controls-footer dvn-button{vertical-align:bottom}mentornity-membership-info-settings-wrapper .columns-container .preview-container{-ms-flex:5;flex:5;height:100%;overflow:auto}mentornity-membership-info-settings-wrapper .columns-container .preview-container dvn-card{max-width:640px;margin-left:auto;margin-right:auto}";

function getViewConfigWrapperForCreation(organisationId, viewName, fields) {
  return {
    dvnAppViewConfig: viewConfig.DvnAppViewConfig.decode({
      type: viewConfig.AppViewType.FormView,
      ui: {
        fields,
      },
    }),
    organisation: new session.ModelReference(organisationId, session.Collection.Organisations),
    viewName,
  };
}
const i18n = {
  formFields: {
    firstName: 'First name',
    lastName: 'Last name',
    title: 'Title',
    bio: 'Bio',
    skills: 'Skills',
    pairLimit: 'Pair limit',
  },
  formTitle: 'My info'
};
const MentornityMembershipInfoSettingsWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.setViewConfigWrapper = (viewConfigWrapper) => {
      // API doesn't add firstName, lastName and subscriptionLimit to the table fields
      viewConfigWrapper.dvnAppViewConfig.table.fields.push(new index$1.TextField('firstName', 'First Name').require(), new index$1.TextField('lastName', 'Last Name').require(), new FieldModelGenerator.NumberField('subscriptionLimit', i18n.formFields.pairLimit));
      viewConfigWrapper.dvnAppViewConfig.title = i18n.formTitle;
      this.viewConfigWrapper = viewConfigWrapper;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail;
      const viewConfigWrapper = session.ViewConfigWrapper.decode(JSON.parse(JSON.stringify(this.viewConfigWrapper)));
      viewConfigWrapper.dvnAppViewConfig.ui.fields = selectedFields.map(sfid => ({ fieldId: sfid }));
      this.viewConfigWrapper = viewConfigWrapper;
    };
    this.onClickSaveChanges = () => {
      const { dvnAppViewConfig } = this.viewConfigWrapper;
      this.api.updateViewConfig(this.viewConfigWrapper._id, { dvnAppViewConfig })
        .then(() => this.notifier.congratulate('Changes are saved.'))
        .catch(() => this.notifier.alert('Saving changes failed.'));
    };
  }
  async componentWillLoad() {
    this.previewFormHandler = new PreviewFormHandler(() => {
      this.notifier.warn('Action unavailable in preview.', 'Preview Mode');
    });
    const { formTarget, organisationId } = this;
    const { headers } = session.getSessionDetails();
    this.api = session.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = wrapperUtil.getAvailableMembershipFormFields(i18n, formTarget, this.organisationConfig);
    const viewName = formTarget === 'mentor'
      ? session.MentornityViewConfigViewName.MentorInfoForm
      : session.MentornityViewConfigViewName.MenteeInfoForm;
    this.api.getViewConfig(organisationId, viewName)
      .then(viewConfigWrapper => {
      this.setViewConfigWrapper(viewConfigWrapper);
    })
      .catch(error => {
      if (error.status === 404) {
        // create the view config
        const fieldRefs = commonWrapperUtil.convertFieldsToFieldReferences(this.availableFields);
        const viewConfigWrapper = getViewConfigWrapperForCreation(organisationId, viewName, fieldRefs);
        this.api.createViewConfig(viewConfigWrapper)
          .then(() => {
          // fetch the created config because API generates table.fields on the fly while getting it
          this.api.getViewConfig(organisationId, viewName)
            .then(viewConfigWrapper => {
            this.setViewConfigWrapper(viewConfigWrapper);
          }).catch(error => this.error = error);
        })
          .catch(error => this.error = error);
      }
      else {
        this.error = error;
      }
    });
  }
  render() {
    const { viewConfigWrapper, availableFields, organisationConfig, } = this;
    if (!organisationConfig || !viewConfigWrapper) {
      return (index.h("div", { class: "d-flex justify-content-center pt-3" }, index.h("dvn-progress", { indefinite: true })));
    }
    const view = Object.assign(Object.assign({}, viewConfigWrapper.dvnAppViewConfig), { handler: this.previewFormHandler });
    const oldMetadataID = ['bio', 'skills', 'title'];
    // find valid fields
    const fieldIdsToUse = {};
    (view.table.fields || []).forEach(usableField => {
      if (!this.organisationConfig.webAppConfiguration.membershipForm || !oldMetadataID.includes(usableField.id)) {
        fieldIdsToUse[usableField.id] = true;
      }
    });
    // display only valid fields
    view.ui.fields = view.ui.fields.filter(field => fieldIdsToUse[field.fieldId]);
    const selectedFields = view.ui.fields.map(field => field.fieldId);
    const options = availableFields.map(field => ({
      label: field.title,
      value: field.id,
      disabled: ['firstName', 'lastName'].includes(field.id)
    }));
    return (index.h(index.Host, null, index.h("mentornity-root-wrapper", null, index.h("div", { class: "columns-container d-flex" }, index.h("div", { class: "controls-container d-flex flex-column" }, index.h("div", { class: "form-controls-container" }, index.h("div", { class: "d-flex flex-column p-3" }, index.h("dvn-alert", { message: "The preview on the right will be updated when there is a change on the controls." }), index.h("dvn-checkbox-group", { options: options, value: selectedFields, onChange: this.onSelectedFieldsChange }))), index.h("div", { class: "controls-footer p-3" }, index.h("dvn-button", { leaned: true, tint: "primary", onClick: this.onClickSaveChanges }, "Save Changes"))), index.h("div", { class: "preview-container" }, index.h("dvn-card", null, index.h("dvn-app-view-form-view", { view: view })))))));
  }
};
index$2.injectNotifier(MentornityMembershipInfoSettingsWrapper);
MentornityMembershipInfoSettingsWrapper.style = mentornityMembershipInfoSettingsWrapperCss;

exports.mentornity_membership_info_settings_wrapper = MentornityMembershipInfoSettingsWrapper;
