import { r as registerInstance, h, H as Host } from './index-102043e0.js';
import './index-ef734a5e.js';
import { D as DateField, a as DateDataType } from './date-ce777316.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-0e8b9ea2.js';
import { T as TextField } from './index-336ef773.js';
import { D as DetailViewConfig } from './detail-view-config-e2344d5e.js';
import { T as TableListViewConfig } from './table-list-view-config-ff8c1b78.js';
import { A as AppViewType } from './view-config-efdeed6d.js';
import { S as SozlukApi } from './index-1e9f4c53.js';
import { d as damgaSpace, I as ID } from './table-list-view-domain-a6c63444.js';
import { A as APIBase } from './kimlikApi-ac700c81.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { c as createMentornityApiInstance, d as MentornityViewConfigViewName } from './instance-fe40f49f.js';
import { m as mentornityApiEndpoint } from './env-4ec3c807.js';
import { g as getSessionDetails } from './session-4127c2a1.js';
import { g as getViewConfigForViewName } from './common-wrapper-util-f1abefff.js';
import { s as sozlukEntries } from './sozluk-entries-e1fd9179.js';
import { D as DataModel } from './data-model-f5160369.js';
import './BaseField-461b6d0c.js';
import './table-config-720f8ea0.js';
import './FieldModelGenerator-ee438a53.js';
import './index-c3eacf05.js';
import './index-a1675f50.js';
import './attachment-32decf79.js';
import './membership-config-68ed7772.js';
import './string-3065a411.js';
import './spaces-c4b46e5e.js';
import './InterceptorHandler-6474bcf4.js';
import './index-47dfc023.js';
import './nested-395a4cd4.js';
import './app-config-d490f9ae.js';
import './services-fc4ce8f3.js';
import './form-view-config-fb04db06.js';
import './actions-b9a0f808.js';
import './membership-821de3c5.js';
import './User-d2ee8b71.js';
import './UserSettings-7b80b841.js';
import './cookie-647f9dc7.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './mentorinty-bridge-api-fc8ad2d8.js';
import './CalendarConfig-cc1e3a80.js';
import './i18n-2b616f25.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;
  }
}

let 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
   */
  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();
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    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;
    }
    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 (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, id: ID, 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, 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: 'mentornity-membership-application-list-view',
    i18nEntryId: 'mentornity-membership-application-list-view',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: 'Applications',
    space: damgaSpace,
    table: generateApplicationsTable(i18n, formViewConfig),
    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' },
          ...(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',
          },
        ],
      },
    }),
  });
};
const detailViewConfig = (i18n, formViewConfig) => {
  if (formViewConfig) {
    formViewConfig.ui.fields.forEach((fieldRef) => {
    });
  }
  return 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 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'),
    ],
  };
}

export { MentornityMembershipApplicationListWrapper as mentornity_membership_application_list_wrapper };
