import { r as registerInstance, h, H as Host } from './index-ecdfb761.js';
import './index-61dcd269.js';
import { D as DateField, a as DateDataType } from './date-1bc489bd.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-23baeeef.js';
import { T as TextField } from './index-150b6a59.js';
import { D as DetailViewConfig } from './detail-view-config-23af2b0d.js';
import { T as TableListViewConfig } from './table-list-view-config-6e2aee35.js';
import { A as AppViewType } from './view-config-1ed8c59f.js';
import { S as SozlukApi } from './index-3bf9b308.js';
import { A as APIBase } from './apiBase-6015f41f.js';
import './data-transfer-field-2f305919.js';
import './filter-cbaa3d7d.js';
import { g as getSessionDetails, m as mentornityApiEndpoint, c as createMentornityApiInstance } from './session-2a491341.js';
import { s as sozlukEntries, M as MentornityMembershipAppListWrapperI18nKey, m as mentornityMembershipAppListWrapperI18nDefault } from './sozluk-entries-1e8f5234.js';
import { D as DataModel } from './data-model-88af49fc.js';
import { b as convertMentornityFieldToDevingenField } from './mentorinty-bridge-api-5ca2d652.js';
import './FieldGenerator-3ae403b2.js';
import './BaseField-0b01dc2c.js';
import './table-config-d73a72ab.js';
import './FieldModelGenerator-378c8613.js';
import './reference-field-a5b414d1.js';
import './index-4e451db4.js';
import './index-09efdc01.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 './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 MembershipApplicationWrapperBridgeApi {
  constructor(organisationId, language, endpoint, headers, onRoleFilterChange) {
    this.client = new APIBase(endpoint, headers);
    this.organisationId = organisationId;
    this.language = language;
    this.onRoleFilterChange = onRoleFilterChange;
  }
  addAuthInterceptor(_token) {
    // console.log('MBA.addAuthInterceptor', token);
  }
  // region DataApi
  get(_collection, _id, _query) {
    return undefined;
  }
  query(_collection, query) {
    var _a;
    const role = ((_a = query.filter) === null || _a === void 0 ? void 0 : _a.filters[0].value) || 'mentors';
    this.onRoleFilterChange(role);
    return new Promise((resolve => {
      this.client.get(`organisations/${this.organisationId}/${role}/applications`).then(response => {
        resolve({
          results: response.results.map(item => DataModel.decode(Object.assign(Object.assign({ _id: item._id, createdAt: item.createdAt, applicationStatus: item.applicationStatus }, (item.data || {})), { 
            // inserted for mentornity-accept-application-button
            role, language: this.language }))),
          meta: {
            total: response.results.length,
          }
        });
      }).catch(e => {
        console.log(e);
      });
    }));
  }
  update(_collection, _id, _body) {
    return undefined;
  }
}

const MentornityMembershipApplicationListWrapper = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.shownRole = 'mentors';
    this.isProgressing = false;
    this.setDictionaryLanguage = async () => {
      this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await this.apiSozluk.getContent(MentornityMembershipAppListWrapperI18nKey, mentornityMembershipAppListWrapperI18nDefault);
    };
    this.onRoleChange = (role) => {
      this.shownRole = role;
    };
  }
  /**
   * Called by mentornity-accept-application-button when an application is accepted.
   * Invalidates the table view to refresh its data.
   * @param event
   */
  onAcceptApplication(event) {
    this.listView.invalidate(event);
  }
  onAction(event) {
    const action = event.detail;
    if (action.name === 'view-application-detail') {
      // called when user clicks the expand button on a table item
      action.params.item.name = `${action.params.item.firstName} ${action.params.item.lastName}`;
      this.viewApplicationDetailDialogActionData = action;
    }
  }
  async componentWillLoad() {
    const { context: { organisationId }, headers } = getSessionDetails();
    // setup strings
    this.setDictionaryLanguage();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, mentornityApiEndpoint, headers, this.onRoleChange);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const organisationConfig = await mentornityApi.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!organisationConfig)
      return;
    this.mentorFields = organisationConfig.metadatas.mentor.map(convertMentornityFieldToDevingenField);
    this.menteeFields = organisationConfig.metadatas.mentee.map(convertMentornityFieldToDevingenField);
    mentornityApi.getMembershipApplicationForm(organisationId, 'mentors')
      .then(mentorApplicationForm => {
      this.mentorApplicationForm = mentorApplicationForm;
    });
    mentornityApi.getMembershipApplicationForm(organisationId, 'mentees')
      .then(menteeApplicationForm => {
      this.menteeApplicationForm = menteeApplicationForm;
    });
  }
  render() {
    var _a;
    const { api, apiSozluk, menteeApplicationForm, mentorApplicationForm, viewApplicationDetailDialogActionData } = this;
    if (!mentorApplicationForm || !menteeApplicationForm) {
      return null;
    }
    const i18n = this.strings;
    const fieldsToUse = this.shownRole === 'mentors' ? this.mentorFields : this.menteeFields;
    const formToUse = this.shownRole === 'mentors' ? this.mentorApplicationForm : this.menteeApplicationForm;
    // filter fields if additional info has been deleted
    const fieldIdsToUse = {};
    (fieldsToUse || []).forEach(usableField => {
      fieldIdsToUse[usableField.id] = true;
    });
    const formFieldRefs = (((_a = formToUse === null || formToUse === void 0 ? void 0 : formToUse.form) === null || _a === void 0 ? void 0 : _a.fields) || []).filter(field => fieldIdsToUse[field.id]);
    const listViewConfig = viewConfig(i18n, fieldsToUse, formFieldRefs);
    return (h(Host, { class: "d-flex flex-grow-1", style: { overflow: 'hidden' } }, h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" }, h("dvn-app-view-list-view-table", { ref: (el) => this.listView = el, apiData: api, apiSozluk: apiSozluk, view: listViewConfig }), viewApplicationDetailDialogActionData &&
      h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.viewApplicationDetailDialogActionData = undefined }, h("dvn-app-view-detail-view-card", { apiSozluk: apiSozluk, id: "user-page", params: {
          itemId: viewApplicationDetailDialogActionData.params.item._id,
          item: viewApplicationDetailDialogActionData.params.item,
        }, view: detailViewConfig(i18n, fieldsToUse, formFieldRefs) })))));
  }
};
const viewConfig = (i18n, fields, fieldRefs) => {
  const columns = {
    'createdAt': {
      width: 150,
    },
    'email': {
      width: 250,
    },
    'firstName': {
      width: 150,
    },
    'lastName': {
      width: 150,
    },
    'actions': {
      width: 150,
    },
  };
  fieldRefs.forEach((fieldRef) => {
    columns[fieldRef.id] = {
      width: 250,
    };
  });
  return TableListViewConfig.decode({
    _id: 'mentornity-membership-application-list-view',
    i18nEntryId: 'mentornity-membership-application-list-view',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: i18n.applications,
    table: generateApplicationsTable(i18n, fields),
    query: {},
    ui: TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        actions: [
          {
            ui: {
              name: 'view-application-detail',
              buttonType: 'icon-button',
              iconName: 'uil uil-expand-alt',
              view: 'flat'
            },
            data: {
              type: 'navigation',
              direction: 'forward',
            }
          },
        ],
        fields: [
          { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
          { fieldId: 'createdAt' },
          { fieldId: 'email' },
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          ...fieldRefs.map((ref => ({ fieldId: ref.id }))),
        ],
        columns,
      },
      quickSearch: {
        fields: [
          {
            field: new SingleChoiceField('role', 'Role', [
              new SingleChoiceFieldOption(i18n.mentorApplications, 'mentors'),
              new SingleChoiceFieldOption(i18n.menteeApplications, 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};
const detailViewConfig = (i18n, fields, fieldRefs) => {
  fieldRefs.forEach((fieldRef) => {
  });
  return DetailViewConfig.decode({
    table: generateApplicationsTable(i18n, fields),
    ui: {
      cardConfig: {
        header: {
          title: {
            fieldId: 'name',
          },
        },
        body: {
          fields: [
            // { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
            { fieldId: 'createdAt' },
            { fieldId: 'email' },
            { fieldId: 'firstName' },
            { fieldId: 'lastName' },
            ...fieldRefs.map((ref => ({ fieldId: ref.id }))),
          ],
        }
      }
    },
  });
};
function generateApplicationsTable(i18n, fields) {
  return {
    fields: [
      new TextField('firstName', i18n.firstName),
      new TextField('lastName', i18n.lastName),
      new TextField('email', i18n.email).setInputType('email'),
      ...fields,
      new DateField('createdAt', i18n.date).setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
    ],
  };
}

export { MentornityMembershipApplicationListWrapper as mentornity_membership_application_list_wrapper };
