import { r as registerInstance, h, H as Host } from './index-ecdfb761.js';
import { i as injectNotifier } from './index-1e6a7311.js';
import { N as NumberField } from './FieldModelGenerator-378c8613.js';
import { T as TextField } from './index-150b6a59.js';
import { D as DvnAppViewConfig, A as AppViewType } from './view-config-1ed8c59f.js';
import './apiBase-6015f41f.js';
import './data-transfer-field-2f305919.js';
import './filter-cbaa3d7d.js';
import { V as ViewConfigWrapper, g as getSessionDetails, c as createMentornityApiInstance, M as ModelReference, C as Collection, m as mentornityApiEndpoint, h as MentornityViewConfigViewName } from './session-2a491341.js';
import { c as convertFieldsToFieldReferences } from './common-wrapper-util-e4afa19b.js';
import { g as getAvailableMembershipFormFields } from './wrapper-util-2b15cdf3.js';
import './state-tunnel-04c0b67a.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-23baeeef.js';
import './index-09efdc01.js';
import './data-model-88af49fc.js';
import './table-config-d73a72ab.js';
import './membership-b6639471.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 './mentorinty-bridge-api-5ca2d652.js';
import './index-e66e8eca.js';
import './attachment-961dd228.js';
import './CalendarConfig-412d1b0f.js';
import './index-3bf9b308.js';
import './sozluk-entries-1e8f5234.js';
import './i18n-09a07b97.js';
import './i18n-0e757ca5.js';
import './calendar-470c802a.js';
import './index-a3ca021c.js';
import './moment-65eca6b3.js';
import './ModifierTrimmer-2f77f917.js';
import './InterceptorHandler-6474bcf4.js';
import './ValidatorLength-f56a7c14.js';
import './form-view-config-e5a5ced8.js';
import './models-f0bc20c6.js';
import './actions-b9a0f808.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: DvnAppViewConfig.decode({
      type: AppViewType.FormView,
      ui: {
        fields,
      },
    }),
    organisation: new ModelReference(organisationId, 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) {
    registerInstance(this, hostRef);
    this.setViewConfigWrapper = (viewConfigWrapper) => {
      // API doesn't add firstName, lastName and subscriptionLimit to the table fields
      viewConfigWrapper.dvnAppViewConfig.table.fields.push(new TextField('firstName', 'First Name').require(), new TextField('lastName', 'Last Name').require(), new NumberField('subscriptionLimit', i18n.formFields.pairLimit));
      viewConfigWrapper.dvnAppViewConfig.title = i18n.formTitle;
      this.viewConfigWrapper = viewConfigWrapper;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail;
      const viewConfigWrapper = 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 } = getSessionDetails();
    this.api = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = getAvailableMembershipFormFields(i18n, formTarget, this.organisationConfig);
    const viewName = formTarget === 'mentor'
      ? MentornityViewConfigViewName.MentorInfoForm
      : MentornityViewConfigViewName.MenteeInfoForm;
    this.api.getViewConfig(organisationId, viewName)
      .then(viewConfigWrapper => {
      this.setViewConfigWrapper(viewConfigWrapper);
    })
      .catch(error => {
      if (error.status === 404) {
        // create the view config
        const fieldRefs = 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 (h("div", { class: "d-flex justify-content-center pt-3" }, 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 (h(Host, null, h("mentornity-root-wrapper", null, h("div", { class: "columns-container d-flex" }, h("div", { class: "controls-container d-flex flex-column" }, h("div", { class: "form-controls-container" }, h("div", { class: "d-flex flex-column p-3" }, h("dvn-alert", { message: "The preview on the right will be updated when there is a change on the controls." }), h("dvn-checkbox-group", { options: options, value: selectedFields, onChange: this.onSelectedFieldsChange }))), h("div", { class: "controls-footer p-3" }, h("dvn-button", { leaned: true, tint: "primary", onClick: this.onClickSaveChanges }, "Save Changes"))), h("div", { class: "preview-container" }, h("dvn-card", null, h("dvn-app-view-form-view", { view: view })))))));
  }
};
injectNotifier(MentornityMembershipInfoSettingsWrapper);
MentornityMembershipInfoSettingsWrapper.style = mentornityMembershipInfoSettingsWrapperCss;

export { MentornityMembershipInfoSettingsWrapper as mentornity_membership_info_settings_wrapper };
