import { TextField } from '@dvn/core/doldurma/src/fields/text';
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, Event, h, Host, Prop, State, Element } from '@stencil/core';
import { mentornityApiEndpoint } from '../../constants/env';
import { getSessionDetails } from '../../util/session';
import { sozlukEntries } from '../sozluk-entries';
import { mentornityAnnouncementWrapperI18nDefault, MentornityAnnouncementWrapperI18nKey } from './i18n';
import { MentornityAnnouncementSelectUsersBridgeApi } from './mentornity-announcement-select-users-bridge-api';
export class MentornityAnnouncementSelectUsers {
  constructor() {
    this.itemsSelectedCount = 0;
    this.shownRole = 'mentor';
    this.isLoading = false;
    this.setDictionaryLanguage = async () => {
      const apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
      this.strings = await apiSozluk.getContent(MentornityAnnouncementWrapperI18nKey, mentornityAnnouncementWrapperI18nDefault);
    };
    this.onFetchingChange = () => {
      this.isLoading = !this.isLoading;
    };
    this.onRoleChange = async (role) => {
      this.setSelectedItems([]);
      this.itemsSelectedCount = 0;
      await this.setAnnouncementRole.emit(role);
    };
    this.onDataChange = (data) => {
      var _a;
      if (this.shownRole === 'mentor' || this.shownRole === 'mentee' || this.shownRole === 'all') {
        this.itemsSelectedCount = (_a = data.results) === null || _a === void 0 ? void 0 : _a.length;
        this.setSelectedItems(data.results);
      }
      this.data = data;
    };
  }
  async componentWillLoad() {
    const { context, headers } = getSessionDetails();
    this.api = new MentornityAnnouncementSelectUsersBridgeApi(context.organisationId, mentornityApiEndpoint, headers, this.organisationConfig, this.onRoleChange, this.onDataChange, this.onFetchingChange);
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    this.setDictionaryLanguage();
  }
  getRole(role) {
    if (role === 'customMentor') {
      return 'mentor';
    }
    else if (role === 'customMentee') {
      return 'mentee';
    }
    else {
      return role;
    }
  }
  render() {
    var _a;
    const { strings } = this;
    if (!strings)
      return;
    const role = this.getRole(this.shownRole);
    const metadata = (_a = this.organisationConfig) === null || _a === void 0 ? void 0 : _a.metadatas[role];
    const listViewConfig = viewConfig(metadata, strings, this.shownRole);
    const isCustomTarget = ['customMentor', 'customMentee'].includes(this.shownRole);
    return (h(Host, { class: "row", style: { overflow: 'hidden' } },
      h("div", { class: "col-12" },
        h("div", { class: "d-flex align-items-center" },
          h("dvn-select", { class: "ml-3", value: 'mentor', onChange: (event) => this.shownRole = event.detail },
            h("dvn-select-option", { value: 'all' }, strings.all),
            h("dvn-select-option", { value: 'mentor' }, strings.mentor),
            h("dvn-select-option", { value: 'customMentor' }, strings.customMentor),
            h("dvn-select-option", { value: 'mentee' }, strings.mentee),
            h("dvn-select-option", { value: 'customMentee' }, strings.customMentee)),
          this.itemsSelectedCount > 0 && h("p", { class: "m-0" }, SozlukApi.build(strings.selectedUsersCount, { count: this.itemsSelectedCount }))),
        !isCustomTarget &&
          h("div", { class: "ml-3", style: {
              margin: '70px auto',
              textAlign: 'center',
              color: 'var(--color-neutral)'
            } }, this.isLoading ?
            h("dvn-progress", { indefinite: true })
            :
              h("p", null, strings.selectedAllTarget))),
      h("div", { class: "col-12" },
        h("dvn-app-view-list-view-table", { key: this.shownRole, apiData: this.api, apiSozluk: this.apiSozluk, view: listViewConfig, style: { height: isCustomTarget ? '500px' : '0px', opacity: isCustomTarget ? '1' : '0' }, onRowSelection: (data) => {
            this.itemsSelectedCount = data === null || data === void 0 ? void 0 : data.length;
            this.setSelectedItems(data);
          }, checkboxSelection: this.shownRole === 'customMentor' || this.shownRole === 'customMentee' ? true : false }))));
  }
  static get is() { return "mentornity-announcement-select-users"; }
  static get properties() { return {
    "language": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "language",
      "reflect": false
    },
    "setSelectedItems": {
      "type": "any",
      "mutable": false,
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "set-selected-items",
      "reflect": false
    },
    "organisationConfig": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Config",
        "resolved": "Config",
        "references": {
          "Config": {
            "location": "import",
            "path": "src/modules/mentornity-js-client/models"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "itemsSelectedCount": {},
    "shownRole": {},
    "data": {},
    "strings": {},
    "isLoading": {}
  }; }
  static get events() { return [{
      "method": "setAnnouncementRole",
      "name": "setAnnouncementRole",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
}
const viewConfig = (metadata, i18n, role) => {
  const columns = {
    'email': {
      width: 300
    }
  };
  (metadata || []).forEach(data => {
    columns[data.id] = {
      width: 200
    };
  });
  return TableListViewConfig.decode({
    _id: 'mentornity-announcement-select-users',
    i18nEntryId: 'mentornity-announcement-select-users',
    type: AppViewType.ListViewTable,
    base: 'mentornity',
    table: {
      name: role,
      fields: [
        new TextField('firstName', i18n.firstName),
        new TextField('lastName', i18n.lastName),
        new TextField('email', i18n.email),
        ...(metadata || []).map(data => new TextField(data.id, data.title))
      ],
    },
    query: {},
    ui: TableListViewConfig.decode({
      main: {
        actionsPlacement: 'left',
        fields: [
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          { fieldId: 'email' },
          ...(metadata || []).map(data => ({ fieldId: data.id }))
        ],
        columns,
      }
    }),
  });
};
