'use strict';

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

const index = require('./index-1ee80297.js');
require('./index-42baafa9.js');
const date = require('./date-25b104f6.js');
const index$3 = require('./index-521d07b9.js');
const index$2 = require('./index-a77c3004.js');
const detailViewConfig$1 = require('./detail-view-config-c107e694.js');
const tableListViewConfig = require('./table-list-view-config-9651a6bc.js');
const viewConfig$1 = require('./view-config-c409ff28.js');
const index$1 = require('./index-b2910095.js');
const tableListViewDomain = require('./table-list-view-domain-a57ad606.js');
const kimlikApi = require('./kimlikApi-1cd43caf.js');
require('./data-transfer-field-0ce05c1a.js');
require('./filter-d5040f65.js');
const instance = require('./instance-8904b0e4.js');
const env = require('./env-56a21d68.js');
const session = require('./session-612c0d2f.js');
const commonWrapperUtil = require('./common-wrapper-util-5385d126.js');
const sozlukEntries = require('./sozluk-entries-34e8486b.js');
const dataModel = require('./data-model-c51de090.js');
require('./BaseField-d019ade6.js');
require('./table-config-be88299b.js');
require('./FieldModelGenerator-2c39c8e9.js');
require('./index-9e7c4ca0.js');
require('./index-30008542.js');
require('./attachment-3090e25e.js');
require('./membership-config-6ba394cc.js');
require('./string-de672b69.js');
require('./spaces-4ce9857b.js');
require('./InterceptorHandler-09a1e84b.js');
require('./index-b1edd71d.js');
require('./nested-8980065f.js');
require('./app-config-e62f5843.js');
require('./services-895a8d1d.js');
require('./form-view-config-36f31520.js');
require('./actions-d7eabd95.js');
require('./membership-14c44e7c.js');
require('./User-286a0714.js');
require('./UserSettings-016122e8.js');
require('./cookie-c4d9848a.js');
require('./_commonjsHelpers-206db00d.js');
require('./index-33e96540.js');
require('./mentorinty-bridge-api-ede51458.js');
require('./CalendarConfig-fed039db.js');
require('./i18n-e6beaec7.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;
  }
}

let 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
   */
  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();
    this.apiSozluk = new index$1.SozlukApi().setLanguage(this.language).setContents(sozlukEntries.sozlukEntries);
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, env.mentornityApiEndpoint, headers, this.onRoleChange);
    const getViewConfigsResponse = await instance.createMentornityApiInstance(env.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;
    }
    const i18n = this.language === 'tr' ? tr : en;
    this.listViewConfig = viewConfig(i18n, this.formViewConfig);
  }
  render() {
    const { api, apiSozluk, formViewConfig, listViewConfig, viewApplicationDetailDialogActionData } = this;
    const i18n = this.language === 'tr' ? tr : en;
    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, id: tableListViewDomain.ID, 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, 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: 'mentornity-membership-application-list-view',
    i18nEntryId: 'mentornity-membership-application-list-view',
    type: viewConfig$1.AppViewType.ListViewTable,
    base: 'mentornity',
    title: 'Applications',
    space: tableListViewDomain.damgaSpace,
    table: generateApplicationsTable(i18n, formViewConfig),
    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' },
          ...(formViewConfig ? formViewConfig.ui.fields : []),
        ],
        columns,
      },
      quickSearch: {
        fields: [
          {
            field: new index$3.SingleChoiceField('role', 'Role', [
              new index$3.SingleChoiceFieldOption('Mentor applications', 'mentors'),
              new index$3.SingleChoiceFieldOption('Mentee applications', 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};
const detailViewConfig = (i18n, formViewConfig) => {
  if (formViewConfig) {
    formViewConfig.ui.fields.forEach((fieldRef) => {
    });
  }
  return detailViewConfig$1.DetailViewConfig.decode({
    table: generateApplicationsTable(i18n, formViewConfig),
    ui: {
      cardConfig: {
        header: {
          title: {
            fieldId: 'name',
          },
        },
        body: {
          fields: [
            // { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
            { fieldId: 'createdAt' },
            { fieldId: 'email' },
            { fieldId: 'firstName' },
            { fieldId: 'lastName' },
            ...(formViewConfig ? formViewConfig.ui.fields : []),
          ],
        }
      }
    },
  });
};
function generateApplicationsTable(i18n, formViewConfig) {
  return {
    fields: [
      new index$2.TextField('firstName', i18n.firstName),
      new index$2.TextField('lastName', i18n.lastName),
      new index$2.TextField('email', i18n.email),
      ...(formViewConfig ? formViewConfig.table.fields : []),
      new date.DateField('createdAt', i18n.date).setDataType(date.DateDataType.Unix).setDateFormat('DD MMM YYYY'),
    ],
  };
}

exports.mentornity_membership_application_list_wrapper = MentornityMembershipApplicationListWrapper;
