import { ResponsiveSize, ResponsiveUIHelper } from '@dvn/alaca/utils/ui';
import { DataModel } from '@dvn/core/models/data-model';
import { ListFetchState } from '@dvn/core/models/list-fetch-state';
import { getPairConfigSelectionConfigForRole, getPairConfigSelectionConfigTargetingRole, PairConfig } from '@dvn/core/models/pair-config';
import { Component, Element, Event, h, Host, Prop, State } from '@stencil/core';
export class DvnAppViewAtamaMemberPairsOverviewView {
  constructor() {
    this.list = ListFetchState.init();
    this.shownTab = 'pairs';
    this.onSizeChange = (size) => {
      this.size = size;
    };
  }
  componentWillLoad() {
    this.fetchMembershipConfigOfMemberToShow();
  }
  componentDidLoad() {
    this.uiHelper = new ResponsiveUIHelper(this.el, this.onSizeChange);
  }
  fetchMembershipConfigOfMemberToShow() {
    var _a;
    const { notifier, view: { table, ui: { i18n } } } = this;
    const { memberToViewRefFieldId } = this.params;
    const memberToShowTableName = (_a = table.fields.find(f => f.type === 'reference' && f.id === memberToViewRefFieldId)) === null || _a === void 0 ? void 0 : _a.otherCollection;
    this.apiUye.getMembershipConfigWithName(memberToShowTableName).then(response => {
      this.membershipConfigToShow = response;
      this.fetchList();
    }, error => notifier.alert(i18n.fetchConfigurationError || 'Getting configuration failed.', error.status));
  }
  fetchList() {
    const { list } = this;
    if (list.isPending) {
      return;
    }
    const { membership, notifier, view: { table, ui: { i18n } } } = this;
    const { userRefFieldId } = this.params;
    this.list = list.beforeFetch();
    this.apiAtama.getPairsOfUser(table.base, table.name, userRefFieldId, membership._id)
      .then(response => this.list = list.afterFetch(response, false), error => {
      this.list = list.afterFetchError(error);
      notifier.alert(i18n.fetchListError || 'Fetching list failed.', error.status);
    });
  }
  onRequestAcceptOrReject() {
    this.fetchList();
  }
  onClickReceivedRequestUser(user) {
    this.action.emit({
      type: 'navigation',
      direction: 'forward',
      resetHistory: true,
      viewId: this.params.viewIdToViewRequestSender,
      params: {
        item: user,
      }
    });
  }
  render() {
    var _a;
    const { list, membershipConfigToShow, shownTab, size, view } = this;
    const { ui: { i18n } } = view;
    const showMobileUI = size < ResponsiveSize.Medium;
    if (!membershipConfigToShow) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    const { memberToViewRefFieldId, userRefFieldId } = this.params;
    // extract the member (to show) data from the pair data
    const itemsToShow = (list.data || [])
      .map(item => {
      const userData = DataModel.decode(item[memberToViewRefFieldId][0]);
      // TODO find another pass the pair id
      userData.pairId = item._id;
      return userData;
    });
    const arePairsFetched = !!list.data;
    const pairConfig = PairConfig.decode(view.table);
    // check if this user needs to see selection UI
    const selectionConfig = getPairConfigSelectionConfigForRole(pairConfig, userRefFieldId);
    // check if this user needs to see approve UI (meaning some other users are selecting this user)
    const selectionConfigTargeted = getPairConfigSelectionConfigTargetingRole(pairConfig, userRefFieldId);
    // show selection active card if the selection is on and the pair limit is more than the active pair count
    const showSelectionActiveCard = arePairsFetched && (selectionConfig === null || selectionConfig === void 0 ? void 0 : selectionConfig.isActive())
      && (selectionConfig.pairLimit === 0 || selectionConfig.pairLimit > itemsToShow.length);
    const showPairList = shownTab === 'pairs' || !showMobileUI;
    const isReceivedRequestListIncluded = !!selectionConfigTargeted;
    const showReceivedRequestList = !!isReceivedRequestListIncluded && (shownTab === 'pair-requests' || !showMobileUI);
    const showHeaders = !showMobileUI;
    return (h(Host, { class: "d-block" },
      showMobileUI && isReceivedRequestListIncluded &&
        h("div", { class: "d-flex justify-content-center pt-3" },
          h("dvn-content-switcher", { options: [
              {
                label: i18n.pairs || 'Pairs',
                value: 'pairs',
              },
              {
                label: i18n.receivedRequests || 'Received Requests',
                value: 'pair-requests',
              },
            ], onChange: (event) => this.shownTab = event.detail, value: this.shownTab })),
      showSelectionActiveCard &&
        h("div", { class: "pt-3" },
          h("dvn-card", { elevation: 0, leaned: true, tint: i18n.selectionCardTint || 'primary' },
            h("dvn-card-header", { slot: "header", tint: i18n.selectionCardTint || 'primary', title: i18n.selectionCardTitle || 'Selection is on!' }),
            i18n.selectionCardMessage || 'You can view all available users and send them requests.',
            h("dvn-card-footer", { slot: "footer", alignRight: true },
              h("dvn-button", { tint: i18n.selectionCardActionTint || 'secondary', onClick: () => this.action.emit({
                  type: 'navigation',
                  direction: 'forward',
                  resetHistory: true,
                  viewId: this.params.viewIdToNavigateToSelectPair,
                }) }, i18n.selectionCardActionLabel || 'Go to selection page')))),
      h("div", { class: "row" },
        showPairList &&
          h("div", { class: {
              'col-md-12 pt-3': true,
              'col-lg-8': showReceivedRequestList,
            } },
            showReceivedRequestList &&
              h("div", { class: "ml-2 mb-2 d-flex align-items-center" },
                showHeaders &&
                  h("small", null,
                    h("b", null, ((_a = i18n.pairs) === null || _a === void 0 ? void 0 : _a.toLocaleUpperCase()) || 'PAIRS'),
                    "\u00A0"),
                (list.isPending && list.data) &&
                  h("dvn-progress", { indefinite: true, size: 14, strokeWidth: 2, tint: "primary" })),
            (list.isPending && !list.data) &&
              h("div", { class: "d-flex justify-content-center" },
                h("dvn-progress", { indefinite: true })),
            list.data &&
              h("div", null, itemsToShow.length > 0
                ? h("dvn-card-list-view", { config: view.ui, fields: membershipConfigToShow.fields, items: itemsToShow })
                : h("dvn-card", { elevation: 0, leaned: true, tint: "warning" }, i18n.noPairsMessage || 'You don\'t have any pairs.'))),
        showReceivedRequestList &&
          h("div", { class: {
              ['col-sm-12 col-md-4 pt-3']: !showMobileUI,
              ['col-sm-12 col-md-12 pt-3']: showMobileUI,
            } },
            h("atama-received-request-list", { i18n: i18n, apiAtama: this.apiAtama, onActionDone: () => this.onRequestAcceptOrReject(), onViewRequestSender: (user) => this.onClickReceivedRequestUser(user), showHeader: showHeaders, table: this.view.table })))));
  }
  static get is() { return "dvn-app-view-atama-member-pairs-overview-view"; }
  static get properties() { return {
    "apiAtama": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AtamaApi",
        "resolved": "AtamaApi",
        "references": {
          "AtamaApi": {
            "location": "import",
            "path": "../../api/atamaApi"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiUye": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "UyeApi",
        "resolved": "UyeApi",
        "references": {
          "UyeApi": {
            "location": "import",
            "path": "@dvn/uye/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "view": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "AtamaMemberPairsOverviewViewConfig",
        "resolved": "AtamaMemberPairsOverviewViewConfig",
        "references": {
          "AtamaMemberPairsOverviewViewConfig": {
            "location": "import",
            "path": "../atama-member-pairs-overview-view-config"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "membership": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Membership",
        "resolved": "Membership",
        "references": {
          "Membership": {
            "location": "import",
            "path": "@dvn/core/models/membership"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "params": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DvnAppViewAtamaMemberPairsOverviewViewParams",
        "resolved": "DvnAppViewAtamaMemberPairsOverviewViewParams",
        "references": {
          "DvnAppViewAtamaMemberPairsOverviewViewParams": {
            "location": "import",
            "path": "./params"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "list": {},
    "membershipConfigToShow": {},
    "size": {},
    "shownTab": {}
  }; }
  static get events() { return [{
      "method": "action",
      "name": "action",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "el"; }
}
