'use strict';

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

const index = require('./index-1141a245.js');
const index$2 = require('./index-f41ad23a.js');
const index$1 = require('./index-a2e99c85.js');
require('./apiBase-e4ebaf8b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const instance = require('./instance-36d7564f.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-0534712d.js');
const session = require('./session-b6f20e12.js');
require('./state-tunnel-786a62ce.js');
require('./BaseField-381327a9.js');
require('./FieldModelGenerator-1900d81a.js');
require('./reference-field-1239b0c3.js');
require('./index-2eea69a0.js');
require('./FieldGenerator-279a646b.js');
require('./date-a24d7714.js');
require('./index-0783d14f.js');
require('./index-e8e4d80b.js');
require('./index-9d3d3d15.js');
require('./index-9fd84b93.js');
require('./index-61f9621a.js');
require('./index-e751cab0.js');
require('./attachment-b0acc4c1.js');
require('./data-model-9afb7f54.js');
require('./membership-ed8d3277.js');
require('./table-config-8b14c7d3.js');
require('./string-de672b69.js');
require('./User-e889279b.js');
require('./CalendarConfig-ee7bb722.js');
require('./UserSettings-fc04eb54.js');
require('./cookie-135bf612.js');
require('./kimlik-api-d3c479a3.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./i18n-49870fc9.js');
require('./i18n-5585a319.js');
require('./calendar-e4b7baeb.js');
require('./index-b776fc14.js');
require('./moment-7a3433f2.js');

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

// removes the HTML entities like &nbsp; from the input
const htmlDecode = (input) => new DOMParser().parseFromString(input, 'text/html').documentElement.textContent;
function getFormDataForCreation(organisationId, formTarget) {
  return {
    title: 'Application Form',
    description: 'Application form for new members.',
    target: formTarget,
    type: 'application',
    form: {
      'fields': [],
      'version': 0.1
    },
    organisation: {
      '_id': organisationId,
      '_class': 'organisations',
      '_type': 'reference'
    },
    status: instance.FormStatus.Unpublished,
  };
}
const MentornityMembershipApplicationSettingsWrapper = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.step = 'description';
    this.editorValue = [
      {
        type: 'h3',
        id: 'form-title',
        value: {
          placeholder: 'Form title',
          text: '',
        },
      },
      {
        type: 'text',
        id: 'form-content',
        value: {
          placeholder: 'Form description',
          text: '',
        },
      },
    ];
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(session.sozlukEntries);
      this.strings = await apiSozluk.getContent(session.MentornityMembershipApplicationSettingsI18nKey, session.mentornityMembershipApplicationSettingsI18nDefault);
    };
    this.setApplicationForm = (form) => {
      this.applicationForm = form;
      const fieldIdsToUse = {};
      (this.targetFields || []).forEach(usableField => {
        fieldIdsToUse[usableField.id] = true;
      });
      this.applicationForm.form.fields = (this.applicationForm.form.fields || []).filter(field => fieldIdsToUse[field.id]);
      // @ts-ignore
      this.applicationForm.description = new showdown.Converter().makeHtml(form.description);
      const editorValue = JSON.parse(JSON.stringify(this.editorValue));
      editorValue[0].value.text = this.applicationForm.title;
      editorValue[1].value.text = this.applicationForm.description;
      this.editorValue = editorValue;
    };
    this.onSelectedFieldsChange = (e) => {
      const selectedFields = e.detail.filter(f => !['email', 'firstName', 'lastName'].includes(f));
      const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
      applicationForm.form.fields = selectedFields.map(sfid => this.availableFields.find(af => af.id === sfid));
      this.applicationForm = applicationForm;
    };
    this.getApplicationLink = () => {
      const { organisationDomain, wlDomain } = this;
      const domain = wlDomain || 'mentornity.com';
      const rootUrl = `https://${domain}/${organisationDomain}/`;
      return this.formTarget === 'mentee' ? `${rootUrl}/mentees/application` : `${rootUrl}/mentors/application`;
    };
    this.onClickSaveChanges = () => {
      const { status, form: { fields: applicationFormFields }, title, description } = this.applicationForm;
      const fields = applicationFormFields.map(f => ({ id: f.id }));
      const data = { form: { fields }, status, title, description };
      this.api.update('forms', this.applicationForm._id, data)
        .then(() => this.notifier.congratulate('Changes are saved.'))
        .catch(() => this.notifier.alert('Saving changes failed.'));
    };
  }
  async componentWillLoad() {
    const { formTarget, organisationId } = this;
    const { headers } = session.getSessionDetails();
    this.api = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    // setup strings
    this.setDictionaryLanguage();
    const config = await this.api.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    this.organisationConfig = config;
    this.availableFields = config.metadatas[formTarget];
    this.targetFields = config.metadatas[formTarget].map(mentorintyBridgeApi.convertMentornityFieldToDevingenField);
    const collection = formTarget === 'mentor' ? 'mentors' : 'mentees';
    this.api.getMembershipApplicationForm(organisationId, collection)
      .then(form => this.setApplicationForm(form))
      .catch(error => {
      if (error.status === 404) {
        const formData = getFormDataForCreation(organisationId, formTarget);
        this.api.createForm(formData)
          .then(createFormResponse => this.setApplicationForm(Object.assign(Object.assign({}, formData), createFormResponse)))
          .catch(error => this.error = error);
      }
      else {
        this.error = error;
      }
    });
  }
  render() {
    const { applicationForm, availableFields, organisationConfig, organisationId, step, strings } = this;
    if (!organisationConfig || !applicationForm) {
      return (index.h("div", { class: "d-flex justify-content-center pt-3" }, index.h("dvn-progress", { indefinite: true })));
    }
    const selectedFields = ['firstName', 'lastName', 'email', ...applicationForm.form.fields.map(field => field.id)];
    const options = [
      { label: 'First name', value: 'firstName', disabled: true },
      { label: 'Last name', value: 'lastName', disabled: true },
      { label: 'Email', value: 'email', disabled: true },
      ...(availableFields).map(field => ({
        label: field.title,
        value: 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: strings.previewWhenUpdate }), index.h("dvn-card", { outlined: true, reverseTint: true, leaned: true }, index.h("div", { class: "d-flex align-items-center" }, index.h("dvn-switch", { scale: "small", shape: "rounded", checked: applicationForm.status === 'published', onChange: () => {
        const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
        applicationForm.status = applicationForm.status === 'published' ? 'unpublished' : 'published';
        this.applicationForm = applicationForm;
      } }), index.h("div", { class: "ml-3" }, applicationForm.status === 'published'
      // flex-row-reverse
      ? index.h("div", { class: `d-flex ${this.language === 'tr' && 'flex-row-reverse'}` }, index.h("span", { class: "mr-1" }, strings.appOpenAndAccessible), index.h("a", { class: "mr-1", href: this.getApplicationLink(), target: "_blank" }, strings.onThisUrl))
      : strings.appsAreClosed))), index.h("div", { class: "mt-3" }, index.h("dvn-content-switcher", { options: [
        {
          label: strings.description,
          value: 'description',
        },
        {
          label: strings.fields,
          value: 'fields',
        },
      ], onChange: e => this.step = e.detail, value: step, shape: "rounded", leaned: true })), step === 'description' &&
      index.h("div", { class: "ml-2 mr-2" }, index.h("dvn-rich-editor", { key: "editor", onChange: (e) => {
          var _a, _b;
          const editorValue = e.detail;
          const applicationForm = JSON.parse(JSON.stringify(this.applicationForm));
          applicationForm.title = htmlDecode((_a = editorValue[0]) === null || _a === void 0 ? void 0 : _a.value.text);
          applicationForm.description = (_b = editorValue[1]) === null || _b === void 0 ? void 0 : _b.value.text;
          this.applicationForm = applicationForm;
          this.editorValue = editorValue;
        }, editorSettings: {
          enableDrag: false,
          enableBlockCreation: false,
          enableBlockDeletion: false,
          hideDragControls: true,
          blockTypes: [],
          blockSettings: {
            text: {
              textSelectionOptions: ['bold', 'link']
            }
          }
        }, value: this.editorValue })), step === 'fields' &&
      index.h("div", { class: "mt-3" }, 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 }, strings.saveChanges))), index.h("div", { class: "preview-container d-flex justify-content-center" }, index.h("mentornity-membership-application-wrapper", { strings: strings, formFromEditor: applicationForm, configFromEditor: organisationConfig, formTarget: this.formTarget, organisationId: organisationId, onAction: () => this.notifier.warn('Action unavailable in preview.', 'Preview Mode') }))))));
  }
};
index$2.injectNotifier(MentornityMembershipApplicationSettingsWrapper);
MentornityMembershipApplicationSettingsWrapper.style = mentornityMembershipApplicationSettingsWrapperCss;

exports.mentornity_membership_application_settings_wrapper = MentornityMembershipApplicationSettingsWrapper;
