import { r as registerInstance, h, H as Host } from './index-55faf181.js';
import './index-6a1cf9c1.js';
import { D as DateField, a as DateDataType } from './date-ce777316.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-083a6906.js';
import { T as TextField } from './index-403e215e.js';
import { T as TableListViewConfig } from './table-list-view-config-8e775e94.js';
import { A as AppViewType } from './view-config-39fd369a.js';
import { I as ID, d as damgaSpace } from './table-list-view-domain-391279b6.js';
import { A as APIBase } from './kimlikApi-7350588e.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { c as createMentornityApiInstance, b as MentornityViewConfigViewName } from './instance-46ab1e99.js';
import { g as getSessionDetails, m as mentornityApiEndpoint } from './session-3ec0aa4c.js';
import { g as getViewConfigForViewName } from './common-wrapper-util-36df331f.js';
import { D as DataModel } from './data-model-f5160369.js';
import './BaseField-461b6d0c.js';
import './index-ebde6a66.js';
import './attachment-32decf79.js';
import './membership-config-a51a5232.js';
import './table-config-5c917348.js';
import './FieldModelGenerator-1ee7fda2.js';
import './index-fa1db470.js';
import './string-3065a411.js';
import './spaces-460b4232.js';
import './InterceptorHandler-6474bcf4.js';
import './index-da37d89d.js';
import './nested-395a4cd4.js';
import './app-config-d490f9ae.js';
import './services-fc4ce8f3.js';
import './form-view-config-00abddd1.js';
import './actions-b9a0f808.js';
import './membership-61c4a2f7.js';
import './User-d2ee8b71.js';
import './UserSettings-7b80b841.js';
import './cookie-93ea205f.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './mentorinty-bridge-api-946adc0d.js';
import './CalendarConfig-184230a0.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 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.isProgressing = false;
    this.onRoleChange = (role) => {
      this.formViewConfig = undefined;
      const viewName = role === 'mentors'
        ? MentornityViewConfigViewName.MentorApplicationForm
        : MentornityViewConfigViewName.MenteeApplicationForm;
      const viewConfigWrapper = 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 } = getSessionDetails();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, mentornityApiEndpoint, headers, this.onRoleChange);
    const getViewConfigsResponse = await createMentornityApiInstance(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 = getViewConfigForViewName(this.viewConfigs, MentornityViewConfigViewName.MentorApplicationForm);
    if (viewConfigWrapper) {
      this.formViewConfig = viewConfigWrapper.dvnAppViewConfig;
    }
  }
  render() {
    const { api, formViewConfig, language } = this;
    const i18n = language === 'tr' ? tr : en;
    return (h(Host, { class: "d-flex flex-grow-1" }, h("mentornity-root-wrapper", { class: "d-flex pl-3 pr-3" }, h("dvn-app-view-list-view-table", { ref: (el) => this.listView = el, id: 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.decode({
    _id: ID,
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: 'Applications',
    space: damgaSpace,
    table: {
      fields: [
        new TextField('firstName', i18n.firstName),
        new TextField('lastName', i18n.lastName),
        new TextField('email', i18n.email),
        ...(formViewConfig ? formViewConfig.table.fields : []),
        new DateField('createdAt', i18n.date).setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
      ],
    },
    query: {},
    ui: 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 SingleChoiceField('role', 'Role', [
              new SingleChoiceFieldOption('Mentor applications', 'mentors'),
              new SingleChoiceFieldOption('Mentee applications', 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};

export { MentornityMembershipApplicationListWrapper as mentornity_membership_application_list_wrapper };
