import { DataModel } from '@dvn/core/models/data-model';
import { SozlukApi } from '@dvn/sozluk/api';
import { Component, 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 { getSessionDetails } from '../../util/session';
import { getPairOverviewViewConfig } from '../mentornity-pairs-overview-wrapper/wrapper-util';
import { sozlukEntries } from '../sozluk-entries';
/**
 * Mentornity web-client has the same event name mapping to consume the events with the same name.
 */
const ViewEvents = {
  openProfilePage: 'dvn.mentornity-member-home-widgets-wrapper.open-profile-page',
  openMeetingDetail: 'dvn.mentornity-member-home-widgets-wrapper.open-meeting-page',
  openMenteesPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentees-page',
  openMentorsPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentors-page',
  openUserPairPage: 'dvn.mentornity-member-home-widgets-wrapper.open-user-pair-page',
  openMentorSelectionPage: 'dvn.mentornity-member-home-widgets-wrapper.open-mentor-selection-page',
};
export class MentornityMemberHomeWidgetsWrapper {
  constructor() {
    this.isPending = true;
  }
  componentWillLoad() {
    this.loadData();
  }
  onAction(event) {
    const action = event.detail;
    switch (action.name) {
      case 'go-to-mentees-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMenteesPage));
        break;
      case 'go-to-mentors-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMentorsPage));
        break;
      case 'go-to-pair-detail-page':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openUserPairPage, {
          detail: {
            userId: action.params.uid,
            subId: action.params.subId,
          }
        }));
        break;
      case 'go-to-mentor-selection':
        // dispatch event for Mentornity web-client to handle the action
        window.dispatchEvent(new CustomEvent(ViewEvents.openMentorSelectionPage));
        break;
    }
  }
  async loadData() {
    const { context, headers } = getSessionDetails(this.groupId);
    const { organisationDomain, organisationId, role, userId } = context;
    this.apiSozluk = new SozlukApi().setLanguage(this.language).setContents(sozlukEntries);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    this.meetingGoalConfig = await mentornityApi.getOrganisationMeetingGoalConfig(organisationDomain)
      .catch(error => this.error = error);
    const memberRolePath = role === 'mentor' ? 'mentors' : 'mentees';
    const meetings = await mentornityApi.getMeetings(organisationId, memberRolePath, userId, {
      status: 'active',
    }).catch(error => this.error = error);
    this.mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    await createMentornityApiInstance(mentornityApiEndpoint, headers)
      .getOrganisationConfig(context.organisationId)
      .then((response) => {
      this.organisationConfig = Config.decode(response);
      this.mentornityBridgeApi.organisationConfig = Config.decode(response);
    });
    const getViewConfigsResponse = await mentornityApi.getViewConfigs(context.organisationId)
      .catch(error => this.error = error);
    if (!getViewConfigsResponse)
      return;
    const viewConfigs = getViewConfigsResponse.results;
    const view = getPairOverviewViewConfig(context, this.language, this.organisationConfig, viewConfigs);
    const membership = DataModel.decode({});
    const userRefFieldId = context.role === 'mentor' ? 'subscribed' : 'subscriber';
    const getPairsResponse = await this.mentornityBridgeApi.getPairsOfUser(view.table.base, view.table.name, userRefFieldId, membership._id)
      .catch(error => this.error = error);
    const activePairs = [];
    const requestedPairs = [];
    const pairsType = context.role === 'mentor' ? 'subscriber' : 'subscribed';
    getPairsResponse.results.forEach(pair => {
      if ((pair === null || pair === void 0 ? void 0 : pair.status) === 'active') {
        activePairs.push({
          user: pair[pairsType][0],
          meetings: meetings.results.filter(meeting => meeting.guests.some(guest => guest._id === pair[pairsType][0]._id))
        });
      }
      else if ((pair === null || pair === void 0 ? void 0 : pair.status) === 'requested') {
        requestedPairs.push({
          user: pair[pairsType][0],
          meetings: meetings.results.filter(meeting => meeting.guests.some(guest => guest._id === pair[pairsType][0]._id))
        });
      }
    });
    this.activePairs = activePairs;
    this.requestedPairs = requestedPairs;
    this.organisationConfig = await mentornityApi.getOrganisationConfig(organisationId);
    this.isPending = false;
  }
  render() {
    const { activePairs, apiSozluk, isPending, menteeType, meetingGoalConfig, organisationConfig, requestedPairs, userType, } = this;
    const showPairMeetingSummaryWidget = meetingGoalConfig && meetingGoalConfig.meetingGoals.length > 0;
    if (!showPairMeetingSummaryWidget) {
      return null;
    }
    return (h(Host, null,
      h("mentornity-root-wrapper", { class: "d-block pt-4", theme: { cornerRadius: '5px' } }, showPairMeetingSummaryWidget &&
        h("mentornity-pair-meeting-summary-widget", { apiSozluk: apiSozluk, isPending: isPending, activePairs: activePairs, organisationConfig: organisationConfig, meetingGoalConfig: meetingGoalConfig, requestedPairs: requestedPairs, userType: userType, menteeType: menteeType }))));
  }
  static get is() { return "mentornity-member-home-widgets-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
    },
    "userType": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "user-type",
      "reflect": false
    },
    "menteeType": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "mentee-type",
      "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
    }
  }; }
  static get states() { return {
    "error": {},
    "meetingGoalConfig": {},
    "activePairs": {},
    "requestedPairs": {},
    "organisationConfig": {},
    "mentornityBridgeApi": {},
    "isPending": {},
    "strings": {}
  }; }
  static get listeners() { return [{
      "name": "action",
      "method": "onAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
