'use strict';

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

const index = require('./index-36b3af04.js');
require('./index-74a00556.js');
const date = require('./date-25b104f6.js');
const index$2 = require('./index-fe19a98b.js');
const index$1 = require('./index-a8f1783c.js');
const tableListViewConfig = require('./table-list-view-config-298c7662.js');
const viewConfig$1 = require('./view-config-ec5f62df.js');
const tableListViewDomain = require('./table-list-view-domain-ffc6c5ab.js');
const kimlikApi = require('./kimlikApi-85c6d3ac.js');
require('./data-transfer-field-0ce05c1a.js');
require('./filter-d5040f65.js');
const instance = require('./instance-79d61640.js');
const session = require('./session-3b788cd7.js');
const commonWrapperUtil = require('./common-wrapper-util-25ff9eca.js');
const dataModel = require('./data-model-c51de090.js');
require('./BaseField-d019ade6.js');
require('./index-d90390f1.js');
require('./attachment-3090e25e.js');
require('./membership-config-707b2c51.js');
require('./table-config-444a77e4.js');
require('./FieldModelGenerator-205dd99c.js');
require('./index-ae305bae.js');
require('./string-de672b69.js');
require('./spaces-2fa9fa10.js');
require('./InterceptorHandler-09a1e84b.js');
require('./index-0cd3bcc0.js');
require('./nested-8980065f.js');
require('./app-config-e62f5843.js');
require('./services-895a8d1d.js');
require('./form-view-config-51279874.js');
require('./actions-d7eabd95.js');
require('./membership-dfbf512e.js');
require('./User-286a0714.js');
require('./UserSettings-016122e8.js');
require('./cookie-370bc992.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./mentorinty-bridge-api-22218ac9.js');
require('./CalendarConfig-9459e520.js');

const en = {
  applicationIsSent: 'Your application is sent.',
  applicationFailed: 'Sending the application failed.',
  firstName: 'First name',
  lastName: 'Last name',
  email: 'Email',
  date: 'Date',
  sendApplication: 'Send Application',
};
const tr = {
  applicationIsSent: 'Başvurunuz gönderildi.',
  applicationFailed: 'Başvuru gönderilirken hata oluştu.',
  firstName: 'İsim',
  lastName: 'Soyisim',
  email: 'E-posta',
  date: 'Tarih',
  sendApplication: 'Başvuruyu Gönder',
};

class MembershipApplicationWrapperBridgeApi {
  constructor(organisationId, language, endpoint, headers, onRoleFilterChange) {
    this.client = new kimlikApi.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.isProgressing = false;
    this.onRoleChange = (role) => {
      this.formViewConfig = undefined;
      const viewName = role === 'mentors'
        ? instance.MentornityViewConfigViewName.MentorApplicationForm
        : instance.MentornityViewConfigViewName.MenteeApplicationForm;
      const viewConfigWrapper = commonWrapperUtil.getViewConfigForViewName(this.viewConfigs, viewName);
      if (viewConfigWrapper) {
        this.formViewConfig = viewConfigWrapper.dvnAppViewConfig;
      }
    };
  }
  /**
   * Called by mentornity-accept-application-button when an application is accepted.
   * Invalidates the table view to refresh its data.
   * @param event
   */
  onAction(event) {
    this.listView.invalidate(event);
  }
  async componentWillLoad() {
    const { context: { organisationId }, headers } = session.getSessionDetails();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, session.mentornityApiEndpoint, headers, this.onRoleChange);
    const getViewConfigsResponse = await instance.createMentornityApiInstance(session.mentornityApiEndpoint, headers)
      .getViewConfigs(organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    this.viewConfigs = getViewConfigsResponse.results;
    // mentor application form is shown by default
    const viewConfigWrapper = commonWrapperUtil.getViewConfigForViewName(this.viewConfigs, instance.MentornityViewConfigViewName.MentorApplicationForm);
    if (viewConfigWrapper) {
      this.formViewConfig = viewConfigWrapper.dvnAppViewConfig;
    }
  }
  render() {
    const { api, formViewConfig, language } = this;
    const i18n = language === 'tr' ? tr : en;
    return (index.h(index.Host, { class: "d-flex flex-grow-1" }, 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, id: tableListViewDomain.ID, apiData: api, view: viewConfig(i18n, formViewConfig) }))));
  }
};
const viewConfig = (i18n, formViewConfig) => {
  const columns = {
    'createdAt': {
      width: 150,
    },
    'email': {
      width: 250,
    },
    'firstName': {
      width: 150,
    },
    'lastName': {
      width: 150,
    },
    'actions': {
      width: 120,
    },
  };
  if (formViewConfig) {
    formViewConfig.ui.fields.forEach((fieldRef) => {
      columns[fieldRef.fieldId] = {
        width: 250,
      };
    });
  }
  return tableListViewConfig.TableListViewConfig.decode({
    _id: tableListViewDomain.ID,
    type: viewConfig$1.AppViewType.ListViewTable,
    base: 'mentornity',
    title: 'Applications',
    space: tableListViewDomain.damgaSpace,
    table: {
      fields: [
        new index$1.TextField('firstName', i18n.firstName),
        new index$1.TextField('lastName', i18n.lastName),
        new index$1.TextField('email', i18n.email),
        ...(formViewConfig ? formViewConfig.table.fields : []),
        new date.DateField('createdAt', i18n.date).setDataType(date.DateDataType.Unix).setDateFormat('DD MMM YYYY'),
      ],
    },
    query: {},
    ui: tableListViewConfig.TableListViewConfig.decode({
      main: {
        fields: [
          { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
          { fieldId: 'createdAt' },
          { fieldId: 'email' },
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          ...(formViewConfig ? formViewConfig.ui.fields : []),
        ],
        columns,
      },
      quickSearch: {
        fields: [
          {
            field: new index$2.SingleChoiceField('role', 'Role', [
              new index$2.SingleChoiceFieldOption('Mentor applications', 'mentors'),
              new index$2.SingleChoiceFieldOption('Mentee applications', 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};

exports.mentornity_membership_application_list_wrapper = MentornityMembershipApplicationListWrapper;
