import { DateField } from '@dvn/core/doldurma/src/fields/date';
import { DateDataType } from '@dvn/core/doldurma/src/fields/date/date';
import { SingleChoiceField, SingleChoiceFieldOption } from '@dvn/core/doldurma/src/fields/single-choice';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { DetailViewConfig } from '@dvn/core/models/detail-view-config';
import { TableListViewConfig } from '@dvn/core/models/table-list-view-config';
import { AppViewType } from '@dvn/core/models/view-config';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, h, Host, Listen, Prop, State } from '@stencil/core';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { sozlukEntries } from '../sozluk-entries';
import { mentornityMembershipAppListWrapperI18nDefault, MentornityMembershipAppListWrapperI18nKey } from './i18n';
import { MembershipApplicationWrapperBridgeApi } from './membership-application-wrapper-bridge-api';
import { convertMentornityFieldToDevingenField } from "../../api/mentorinty-bridge-api";
export class MentornityMembershipApplicationListWrapper {
  constructor() {
    this.shownRole = 'mentors';
    this.isProgressing = false;
    this.setDictionaryLanguage = async () => {
      this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await this.apiSozluk.getContent(MentornityMembershipAppListWrapperI18nKey, mentornityMembershipAppListWrapperI18nDefault);
    };
    this.onRoleChange = (role) => {
      this.shownRole = role;
    };
  }
  /**
   * 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();
    // setup strings
    this.setDictionaryLanguage();
    this.api = new MembershipApplicationWrapperBridgeApi(organisationId, this.language, mentornityApiEndpoint, headers, this.onRoleChange);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const organisationConfig = await mentornityApi.getOrganisationConfig(organisationId)
      .catch(error => this.error = error);
    if (!organisationConfig)
      return;
    this.mentorFields = organisationConfig.metadatas.mentor.map(convertMentornityFieldToDevingenField);
    this.menteeFields = organisationConfig.metadatas.mentee.map(convertMentornityFieldToDevingenField);
    mentornityApi.getMembershipApplicationForm(organisationId, 'mentors')
      .then(mentorApplicationForm => {
      this.mentorApplicationForm = mentorApplicationForm;
    });
    mentornityApi.getMembershipApplicationForm(organisationId, 'mentees')
      .then(menteeApplicationForm => {
      this.menteeApplicationForm = menteeApplicationForm;
    });
  }
  render() {
    var _a;
    const { api, apiSozluk, menteeApplicationForm, mentorApplicationForm, viewApplicationDetailDialogActionData } = this;
    if (!mentorApplicationForm || !menteeApplicationForm) {
      return null;
    }
    const i18n = this.strings;
    const fieldsToUse = this.shownRole === 'mentors' ? this.mentorFields : this.menteeFields;
    const formToUse = this.shownRole === 'mentors' ? this.mentorApplicationForm : this.menteeApplicationForm;
    // filter fields if additional info has been deleted
    const fieldIdsToUse = {};
    (fieldsToUse || []).forEach(usableField => {
      fieldIdsToUse[usableField.id] = true;
    });
    const formFieldRefs = (((_a = formToUse === null || formToUse === void 0 ? void 0 : formToUse.form) === null || _a === void 0 ? void 0 : _a.fields) || []).filter(field => fieldIdsToUse[field.id]);
    const listViewConfig = viewConfig(i18n, fieldsToUse, formFieldRefs);
    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, fieldsToUse, formFieldRefs) })))));
  }
  static get is() { return "mentornity-membership-application-list-wrapper"; }
  static get properties() { return {
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": "Used to show proper translations, passed by the parent component."
      },
      "attribute": "language",
      "reflect": false
    }
  }; }
  static get states() { return {
    "mentorFields": {},
    "menteeFields": {},
    "shownRole": {},
    "mentorApplicationForm": {},
    "menteeApplicationForm": {},
    "formViewConfig": {},
    "viewConfigs": {},
    "listViewConfig": {},
    "detailViewConfig": {},
    "error": {},
    "isProgressing": {},
    "strings": {},
    "viewApplicationDetailDialogActionData": {}
  }; }
  static get listeners() { return [{
      "name": "acceptApplication",
      "method": "onAcceptApplication",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
const viewConfig = (i18n, fields, fieldRefs) => {
  const columns = {
    'createdAt': {
      width: 150,
    },
    'email': {
      width: 250,
    },
    'firstName': {
      width: 150,
    },
    'lastName': {
      width: 150,
    },
    'actions': {
      width: 150,
    },
  };
  fieldRefs.forEach((fieldRef) => {
    columns[fieldRef.id] = {
      width: 250,
    };
  });
  return TableListViewConfig.decode({
    _id: 'mentornity-membership-application-list-view',
    i18nEntryId: 'mentornity-membership-application-list-view',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    title: i18n.applications,
    table: generateApplicationsTable(i18n, fields),
    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' },
          ...fieldRefs.map((ref => ({ fieldId: ref.id }))),
        ],
        columns,
      },
      quickSearch: {
        fields: [
          {
            field: new SingleChoiceField('role', 'Role', [
              new SingleChoiceFieldOption(i18n.mentorApplications, 'mentors'),
              new SingleChoiceFieldOption(i18n.menteeApplications, 'mentees'),
            ]).setValue('mentors'),
          }
        ],
        fieldUIConfigs: [
          {
            fieldId: 'role',
            width: '200px',
          },
        ],
      },
    }),
  });
};
const detailViewConfig = (i18n, fields, fieldRefs) => {
  const columns = {
    'createdAt': {
      width: 150,
    },
    'email': {
      width: 250,
    },
    'firstName': {
      width: 150,
    },
    'lastName': {
      width: 150,
    },
    'actions': {
      width: 120,
    },
  };
  fieldRefs.forEach((fieldRef) => {
    columns[fieldRef.id] = {
      width: 250,
    };
  });
  return DetailViewConfig.decode({
    table: generateApplicationsTable(i18n, fields),
    ui: {
      cardConfig: {
        header: {
          title: {
            fieldId: 'name',
          },
        },
        body: {
          fields: [
            // { fieldDisplay: { id: 'actions' }, componentTag: 'mentornity-accept-application-button' },
            { fieldId: 'createdAt' },
            { fieldId: 'email' },
            { fieldId: 'firstName' },
            { fieldId: 'lastName' },
            ...fieldRefs.map((ref => ({ fieldId: ref.id }))),
          ],
        }
      }
    },
  });
};
function generateApplicationsTable(i18n, fields) {
  return {
    fields: [
      new TextField('firstName', i18n.firstName),
      new TextField('lastName', i18n.lastName),
      new TextField('email', i18n.email).setInputType('email'),
      ...fields,
      new DateField('createdAt', i18n.date).setDataType(DateDataType.Unix).setDateFormat('DD MMM YYYY'),
    ],
  };
}
