import { r as registerInstance, h, H as Host } from './index-b7735e0d.js';
import './index-7b119e61.js';
import { D as DateField, a as DateDataType } from './date-ce777316.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-80ec23ef.js';
import { T as TextField } from './index-403101cb.js';
import { D as DetailViewConfig } from './detail-view-config-59c98d8d.js';
import { T as TableListViewConfig } from './table-list-view-config-99e5c0fd.js';
import { A as AppViewType } from './view-config-dfb61752.js';
import { S as SozlukApi } from './index-1e9f4c53.js';
import { A as APIBase } from './apiBase-d573f009.js';
import './data-transfer-field-918730a3.js';
import './filter-cbaa3d7d.js';
import { c as createMentornityApiInstance, d as MentornityViewConfigViewName } from './instance-7b02ef1d.js';
import { m as mentornityApiEndpoint } from './env-4ec3c807.js';
import { g as getSessionDetails } from './session-b16a440c.js';
import { g as getViewConfigForViewName } from './common-wrapper-util-289d199c.js';
import { s as sozlukEntries } from './sozluk-entries-849428da.js';
import { D as DataModel } from './data-model-f7ccf826.js';
import './BaseField-461b6d0c.js';
import './table-config-0c06fb1f.js';
import './FieldModelGenerator-020f4a04.js';
import './reference-field-0e7cd534.js';
import './index-1d3efe49.js';
import './index-eb14fd2d.js';
import './index-4c39b6a6.js';
import './membership-e92743d1.js';
import './string-3065a411.js';
import './User-1ef5a482.js';
import './UserSettings-27df01e6.js';
import './cookie-1686830b.js';
import './kimlikApi-0d7e6ce7.js';
import './_commonjsHelpers-27f122dd.js';
import './index-d3bd30bd.js';
import './index-774783ee.js';
import './attachment-32decf79.js';
import './mentorinty-bridge-api-78ab1153.js';
import './CalendarConfig-88c2213e.js';
import './i18n-e90027e3.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, 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',
    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 };
