'use strict';

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

const index = require('./index-1141a245.js');
require('./index-2eea69a0.js');
const date = require('./date-a24d7714.js');
const index$3 = require('./index-9d3d3d15.js');
const index$2 = require('./index-61f9621a.js');
const detailViewConfig$1 = require('./detail-view-config-4fe32db3.js');
const tableListViewConfig = require('./table-list-view-config-5eaa0344.js');
const viewConfig$1 = require('./view-config-7972654b.js');
const index$1 = require('./index-a2e99c85.js');
const apiBase = require('./apiBase-e4ebaf8b.js');
require('./data-transfer-field-e8417d5f.js');
require('./filter-d5040f65.js');
const instance = require('./instance-36d7564f.js');
const session = require('./session-b6f20e12.js');
const dataModel = require('./data-model-9afb7f54.js');
const mentorintyBridgeApi = require('./mentorinty-bridge-api-0534712d.js');
require('./FieldGenerator-279a646b.js');
require('./BaseField-381327a9.js');
require('./table-config-8b14c7d3.js');
require('./FieldModelGenerator-1900d81a.js');
require('./reference-field-1239b0c3.js');
require('./index-0783d14f.js');
require('./index-e8e4d80b.js');
require('./index-9fd84b93.js');
require('./membership-ed8d3277.js');
require('./string-de672b69.js');
require('./User-e889279b.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');
require('./index-e751cab0.js');
require('./attachment-b0acc4c1.js');
require('./CalendarConfig-ee7bb722.js');

class MembershipApplicationWrapperBridgeApi {
  constructor(organisationId, language, endpoint, headers, onRoleFilterChange) {
    this.client = new apiBase.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.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) {
    index.registerInstance(this, hostRef);
    this.shownRole = 'mentors';
    this.isProgressing = false;
    this.setDictionaryLanguage = async () => {
      this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(session.sozlukEntries);
      this.strings = await this.apiSozluk.getContent(session.MentornityMembershipAppListWrapperI18nKey, session.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 } = session.getSessionDetails();
    // setup strings
    this.setDictionaryLanguage();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, session.mentornityApiEndpoint, headers, this.onRoleChange);
    const mentornityApi = instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers);
    const organisationConfig = await mentornityApi.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!organisationConfig)
      return;
    this.mentorFields = organisationConfig.metadatas.mentor.map(mentorintyBridgeApi.convertMentornityFieldToDevingenField);
    this.menteeFields = organisationConfig.metadatas.mentee.map(mentorintyBridgeApi.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 (index.h(index.Host, { class: "d-flex flex-grow-1", style: { overflow: 'hidden' } }, index.h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" }, index.h("dvn-app-view-list-view-table", { ref: (el) => this.listView = el, apiData: api, apiSozluk: apiSozluk, view: listViewConfig }), viewApplicationDetailDialogActionData &&
      index.h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.viewApplicationDetailDialogActionData = undefined }, index.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.TableListViewConfig.decode({
    _id: 'mentornity-membership-application-list-view',
    i18nEntryId: 'mentornity-membership-application-list-view',
    type: viewConfig$1.AppViewType.ListViewTable,
    base: 'mentornity',
    title: i18n.applications,
    table: generateApplicationsTable(i18n, fields),
    query: {},
    ui: tableListViewConfig.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 index$3.SingleChoiceField('role', 'Role', [
              new index$3.SingleChoiceFieldOption(i18n.mentorApplications, 'mentors'),
              new index$3.SingleChoiceFieldOption(i18n.menteeApplications, 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};
const detailViewConfig = (i18n, fields, fieldRefs) => {
  fieldRefs.forEach((fieldRef) => {
  });
  return detailViewConfig$1.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 index$2.TextField('firstName', i18n.firstName),
      new index$2.TextField('lastName', i18n.lastName),
      new index$2.TextField('email', i18n.email).setInputType('email'),
      ...fields,
      new date.DateField('createdAt', i18n.date).setDataType(date.DateDataType.Unix).setDateFormat('DD MMM YYYY'),
    ],
  };
}

exports.mentornity_membership_application_list_wrapper = MentornityMembershipApplicationListWrapper;
