import CalendarUtils from '@dvn/core/util/calendar';
import { User } from '@dvn/kimlik/api/models';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, Element, h, Host, Listen, Prop, State } from '@stencil/core';
import { createMentornityApiInstance } from '../../../../mentornity-js-client';
import { Config } from '../../../../mentornity-js-client/models';
import { MentornityBridgeApi } from '../../api/mentorinty-bridge-api';
import { mentornityApiEndpoint } from '../../constants/env';
import { generateMembershipForRole, getSessionDetails, getUserSettings } from '../../util/session';
import { sozlukCalendarEntryEn, sozlukCalendarEntryPtBr, sozlukCalendarEntryTr } from '../sozluk-calendar-entries';
import { sozlukEntries } from '../sozluk-entries';
import { getUserCardListViewConfig, getUserDetailDialogViewConfig } from './wrapper-util';
export class MentornityUserCardListWrapper {
  constructor() {
    this.weekStartDay = 'monday';
  }
  async componentWillLoad() {
    const { isZoomAuthenticated, language, timeFormat, dateFormat, timeZone, viewedUserRole, weekStartDay, } = this;
    // set user's locale and time zone
    CalendarUtils.setTimeFormat(timeFormat);
    CalendarUtils.setTimeZone(timeZone);
    CalendarUtils.setDateFormat(dateFormat);
    switch (language) {
      case 'pt-br':
        CalendarUtils.setLocale(language, sozlukCalendarEntryPtBr, weekStartDay);
        break;
      case 'tr':
        CalendarUtils.setLocale(language, sozlukCalendarEntryTr, weekStartDay);
        break;
      default:
        CalendarUtils.setLocale(language, sozlukCalendarEntryEn, weekStartDay);
        break;
    }
    this.apiSozluk = new SozlukApi().setLanguage(language).setContents(sozlukEntries);
    const { context, headers } = getSessionDetails(this.groupId);
    this.mentornityCookieContext = context;
    this.userSettings = getUserSettings(timeFormat, dateFormat, timeZone, language, isZoomAuthenticated, weekStartDay);
    this.mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    const user = await mentornityApi.get('users', context.userId)
      .catch(error => this.error = error);
    if (!user)
      return;
    this.user = User.decode(user);
    const config = await mentornityApi.getOrganisationConfig(context.organisationId)
      .catch(error => this.error = error);
    if (!config)
      return;
    if (context.role === 'mentee' && config.menteeType === 'group') {
      this.membership = generateMembershipForRole('group');
    }
    else {
      this.membership = generateMembershipForRole(context.role);
    }
    this.guestToPassToAvailableTimePickerAsCurrentUser = this.user;
    if (context.role === 'mentee' && config.menteeType === 'group') {
      // fetch the group of the mentee and set as the guest instead of the mentee
      if (context.groupId) {
        const group = await mentornityApi.getGroup(context.groupId).catch(error => this.error = error);
        if (group) {
          this.guestToPassToAvailableTimePickerAsCurrentUser = Object.assign(Object.assign({}, group), { name: group.title, initials: group.title[0] });
        }
      }
      else {
        this.guestToPassToAvailableTimePickerAsCurrentUser = undefined;
      }
    }
    const organisationConfig = Config.decode(config);
    this.organisationConfig = organisationConfig;
    this.mentornityBridgeApi.organisationConfig = organisationConfig;
    this.userCardListViewConfig = getUserCardListViewConfig(context, language, organisationConfig, viewedUserRole, {
      mentornityBridgeApi: this.mentornityBridgeApi,
      apiSozluk: this.apiSozluk,
      guestToPassToAvailableTimePickerAsCurrentUser: this.guestToPassToAvailableTimePickerAsCurrentUser,
      userSettings: this.userSettings,
      membership: this.membership,
    });
    this.userDetailDialogViewConfig = getUserDetailDialogViewConfig(context, language, organisationConfig, viewedUserRole);
  }
  componentDidRender() {
    var _a, _b;
    (_b = (_a = this.el.querySelector(`dvn-app-view-list-view-card`)) === null || _a === void 0 ? void 0 : _a.retainPosition) === null || _b === void 0 ? void 0 : _b.call(_a);
  }
  onAction(event) {
    const action = event.detail;
    switch (action.name) {
      case 'view-details':
        this.userToViewDetails = action.params.item;
        break;
      case 'go-to-profile-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent('dvn.mentornity-user-card-list-wrapper.open-profile-page', {
          detail: {
            user: action.params.item,
          }
        }));
        break;
      case 'open-meeting-detail-after-creation':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent('dvn.mentornity-user-card-list-wrapper.open-meeting-page', {
          detail: {
            meetingId: action.params.meetingId,
          }
        }));
        break;
    }
  }
  render() {
    const { apiSozluk, mentornityBridgeApi, userCardListViewConfig, userToViewDetails, userDetailDialogViewConfig, } = this;
    if (!userCardListViewConfig) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    return (h(Host, { style: { display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' } },
      h("mentornity-root-wrapper", null,
        h("div", { style: { display: 'flex', overflow: 'hidden', flexDirection: 'column' } },
          this.alertMessage &&
            h("dvn-alert", { tint: "warning", message: this.alertMessage, extraClass: "mt-3 ml-3 mr-3" },
              h("dvn-card-footer", { slot: "footer", "align-right": true },
                h("dvn-button", { leaned: true, tint: "secondary", view: "flat", onClick: () => window.dispatchEvent(new CustomEvent('dvn.mentornity-user-card-list-wrapper.alert-message-click')) }, this.alertActionLabel))),
          h("dvn-app-view-list-view-card", { apiData: mentornityBridgeApi, apiSozluk: apiSozluk, view: userCardListViewConfig })),
        userToViewDetails &&
          h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.userToViewDetails = undefined },
            h("dvn-app-view-detail-view-card", { apiData: mentornityBridgeApi, apiSozluk: apiSozluk, id: "user-page", params: {
                itemId: userToViewDetails._id,
              }, view: userDetailDialogViewConfig })))));
  }
  static get is() { return "mentornity-user-card-list-wrapper"; }
  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
    },
    "timeZone": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "time-zone",
      "reflect": false
    },
    "timeFormat": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "time-format",
      "reflect": false
    },
    "dateFormat": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "date-format",
      "reflect": false
    },
    "weekStartDay": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'monday' | 'saturday' | 'sunday'",
        "resolved": "\"monday\" | \"saturday\" | \"sunday\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "week-start-day",
      "reflect": false,
      "defaultValue": "'monday'"
    },
    "isZoomAuthenticated": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "is-zoom-authenticated",
      "reflect": false
    },
    "organisationId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "organisation-id",
      "reflect": false
    },
    "groupId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "group-id",
      "reflect": false
    },
    "viewedUserRole": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "'mentee' | 'mentor'",
        "resolved": "\"mentee\" | \"mentor\"",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "viewed-user-role",
      "reflect": false
    },
    "alertMessage": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "alert-message",
      "reflect": false
    },
    "alertActionLabel": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "alert-action-label",
      "reflect": false
    }
  }; }
  static get states() { return {
    "organisationConfig": {},
    "organisationViewConfigs": {},
    "error": {},
    "userCardListViewConfig": {},
    "userDetailDialogViewConfig": {},
    "guestToPassToAvailableTimePickerAsCurrentUser": {},
    "userToViewDetails": {}
  }; }
  static get elementRef() { return "el"; }
  static get listeners() { return [{
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
