"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf3 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _react = _interopRequireWildcard(require("react"));

var immutable = _interopRequireWildcard(require("immutable"));

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

var _IconPlus = _interopRequireDefault(require("@instructure/ui-icons/lib/Line/IconPlus"));

var _BreadcrumbLink = _interopRequireDefault(require("@instructure/ui-breadcrumb/lib/components/Breadcrumb/BreadcrumbLink"));

var _Button = _interopRequireDefault(require("@instructure/ui-buttons/lib/components/Button"));

var _Heading = _interopRequireDefault(require("@instructure/ui-elements/lib/components/Heading"));

var _AccessibleContent = _interopRequireDefault(require("@instructure/ui-a11y/lib/components/AccessibleContent"));

var _lib = _interopRequireDefault(require("@instructure/ui-themeable/lib"));

var _Bank = _interopRequireDefault(require("../../../common/records/Bank"));

var _Page = _interopRequireDefault(require("../../../common/components/layout/Page"));

var _PaginatedCollection = _interopRequireDefault(require("../../../common/components/shared/PaginatedCollection"));

var _QuizEntry = _interopRequireDefault(require("../../../common/records/QuizEntry"));

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));

var _debounceLatestPromise = _interopRequireDefault(require("../../../common/util/debounceLatestPromise"));

var _AddBankEntryModal = _interopRequireDefault(require("../../../banks/components/AddBankEntryModal"));

var _BankEntriesList = _interopRequireDefault(require("../../../banks/components/BankEntriesList"));

var _BankSearch = _interopRequireDefault(require("../../../banks/components/BankSearch"));

var _HeaderMenu = _interopRequireDefault(require("../../../banks/components/HeaderMenu"));

var _NavWrapper = _interopRequireDefault(require("../NavWrapper"));

var _constants = require("@instructure/quiz-common/lib/constants");

var _theme = _interopRequireDefault(require("./theme"));

var _dec,
    _class,
    _class2,
    _temp,
    _default_nl_number = Intl.NumberFormat("nl", { style: "decimal" }).format;

var styles = {
  componentId: 'fWUWr',
  template: function template(theme) {
    return "\n\n.fWUWr_caGd{background-color:".concat(theme.contentBackgroundColor || 'inherit', ";padding:").concat(theme.contentPaddingTopBottom || 'inherit', " ").concat(theme.contentPaddingLeftRight || 'inherit', "}\n\n.fWUWr_bXVg,.fWUWr_fDcJ,.fWUWr_dGfM{align-items:center;display:flex;flex-direction:row}\n\n.fWUWr_bXVg{flex:50%}\n\n.fWUWr_dGfM{flex:50%;justify-content:flex-end}\n\n.fWUWr_cfIL{padding:0 0 ").concat(theme.bankNamePaddingBottom || 'inherit', " 0}\n\n.fWUWr_etkf{padding-top:0.25rem;width:2rem}\n\n@media screen and (--phoneBreakPoint){.fWUWr_caGd{padding:").concat(theme.phoneContentPadding || 'inherit', " 0}}");
  },
  'content': 'fWUWr_caGd',
  'topLeftMenu': 'fWUWr_bXVg',
  'topMenu': 'fWUWr_fDcJ',
  'topRightMenu': 'fWUWr_dGfM',
  'bankName': 'fWUWr_cfIL',
  'loading': 'fWUWr_etkf'
};
var Bank = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(Bank, _Component);

  function Bank() {
    var _getPrototypeOf2;

    var _this;

    (0, _classCallCheck2.default)(this, Bank);

    for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
      _args[_key] = arguments[_key];
    }

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(Bank)).call.apply(_getPrototypeOf2, [this].concat(_args)));

    _this.openAddBankEntryModal = function () {
      _this.props.openModal(_constants.ADD_BANK_ENTRY_MODAL, {
        modalTrigger: _this.createBankEntryButton
      });
    };

    _this.renderHeaderMenu = function () {
      if (!_this.props.isCompact) {
        return _react.default.createElement(_HeaderMenu.default, {
          bank: _this.props.bank
        });
      }
    };

    _this.storeCreateBankEntryButtonRef = function (c) {
      _this.createBankEntryButton = c;
    };

    _this.addBankToQuiz = function () {
      var newEntry = _QuizEntry.default.create({
        entryId: _this.props.bankId,
        entryType: 'Bank',
        position: _this.props.position,
        stimulusQuizEntryId: _this.props.stimulusId
      });

      _this.props.addEntryToQuiz(_this.props.activeQuizId, newEntry.entryId, newEntry.entryType, newEntry.getProperties(), false).then(function () {
        _this.props.screenreaderNotification("Bank is toegevoegd aan de toets");
      });
    };

    _this.renderTopLeftMenu = function () {
      return _react.default.createElement("div", {
        className: styles.topLeftMenu
      }, _this.renderMultiAdd());
    };

    _this.renderTopRightMenu = function () {
      return _react.default.createElement("div", {
        className: styles.topRightMenu
      }, _this.renderNewBankEntryButton());
    };

    _this.announceResults = function (_ref) {
      var _s, _n, _i, _v;

      var totalPages = _ref.totalPages;
      var message = (_s = totalPages, _n = +_s, _n === 0 ? "Geen zoekresultaten gevonden" : (_i = Math.floor(Math.abs(+_s)), _v = (_s + '.').split('.')[1].length, _i === 1 && _v === 0 ? "Er wordt \xE9\xE9n pagina met resultaten weergegeven" : "Er worden " + _default_nl_number(totalPages) + " pagina's met resultaten weergegeven")); // Audibly announce when search results are ready.
      // We debounce using a larger interval for a11y, so that the user isn't
      // flooded with "Search results ready" messages every time they type a
      // character

      _this.props.screenreaderNotification(message);
    };

    _this.debouncedAnnounceResults = (0, _debounce.default)(_this.announceResults, 1000);

    _this.getPage = function (page, search) {
      var _this$props = _this.props,
          getBankEntries = _this$props.getBankEntries,
          bankId = _this$props.bankId,
          useBankSearch = _this$props.useBankSearch;
      var text = search.get('text');
      var interactionTypes = search.get('interactionTypes', immutable.Set()).toJS();
      var tagIds = search.get('tags', []).map(function (tag) {
        return tag.id;
      });
      var filters = {
        interactionTypes: interactionTypes,
        tags: tagIds
      };
      var params = {
        page: page,
        text: text,
        filters: filters
      };
      var resultPage = getBankEntries(bankId, useBankSearch, params);

      if (resultPage) {
        return resultPage.then(function (results) {
          _this.debouncedAnnounceResults(results);

          return results;
        });
      } else {
        return Promise.resolve(null);
      }
    };

    _this.getPageDebounced = (0, _debounceLatestPromise.default)(function () {
      var _this2;

      return (_this2 = _this).getPage.apply(_this2, arguments);
    }, 100);

    _this.renderRecords = function (recordIds) {
      var addEntryFunc = _this.props.isCompact && _this.props.addEntryToQuiz || null;
      return _react.default.createElement(_BankEntriesList.default, {
        addEntryToQuiz: addEntryFunc,
        bankId: _this.props.bankId,
        navigateToBankEntry: _this.props.navigateToBankEntry,
        recordIds: recordIds
      });
    };

    return _this;
  }

  (0, _createClass2.default)(Bank, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.props.resetSearch(this.props.bankId);

      if (this.props.onError) {
        this.props.getBank(this.props.bankId).catch(this.props.onError);
      } else {
        this.props.getBank(this.props.bankId);
      }
    }
  }, {
    key: "renderNav",
    value: function renderNav() {
      return _react.default.createElement(_NavWrapper.default, {
        closeTray: this.props.closeTray,
        navigateToBanks: this.props.navigateToBanks,
        navigateToBuild: this.props.navigateToBuild,
        renderHeaderMenu: this.renderHeaderMenu
      }, _react.default.createElement(_BreadcrumbLink.default, {
        key: "bank"
      }, this.props.bank.title));
    }
  }, {
    key: "renderName",
    value: function renderName() {
      return _react.default.createElement("div", {
        className: styles.bankName
      }, _react.default.createElement(_Heading.default, {
        level: "h1"
      }, this.props.bank.title));
    }
  }, {
    key: "renderAddBankEntryModal",
    value: function renderAddBankEntryModal() {
      if (!this.props.isCompact) {
        return _react.default.createElement(_AddBankEntryModal.default, {
          bankId: this.props.bankId,
          navigateToBankEntry: this.props.navigateToBankEntry
        });
      }
    }
  }, {
    key: "renderModals",
    value: function renderModals() {
      return _react.default.createElement("div", null, this.renderAddBankEntryModal());
    }
  }, {
    key: "renderNewBankEntryButton",
    value: function renderNewBankEntryButton() {
      if (!this.props.isCompact) {
        return _react.default.createElement(_Button.default, {
          margin: "small none",
          ref: this.storeCreateBankEntryButtonRef,
          variant: "primary",
          onClick: this.openAddBankEntryModal,
          "data-automation": "sdk-new-bank-entry-button",
          icon: _IconPlus.default
        }, _react.default.createElement(_AccessibleContent.default, {
          alt: "Bankvermelding maken"
        }, "Nieuw"));
      }
    }
  }, {
    key: "renderMultiAdd",
    value: function renderMultiAdd() {
      var isEmpty = this.props.bank.itemEntryCount === 0;

      if (this.props.isCompact && !isEmpty) {
        return _react.default.createElement(_Button.default, {
          onClick: this.addBankToQuiz,
          margin: "small none",
          icon: _IconPlus.default
        }, _react.default.createElement(_AccessibleContent.default, {
          alt: "Deze bank toevoegen aan test"
        }, "Alles / Willekeurig"));
      }
    }
  }, {
    key: "stateKey",
    value: function stateKey() {
      return "".concat(_constants.BANKS_BANK_ENTRY_PAGINATION, ":").concat(this.props.bankId);
    }
  }, {
    key: "renderSearch",
    value: function renderSearch() {
      if (this.props.bank.filters !== null && this.props.useBankSearch) {
        var its = this.props.bank.filters.interaction_types;
        var tags = this.props.bank.filters.tags;
        return _react.default.createElement(_BankSearch.default, {
          interactionTypes: its,
          tags: tags,
          pageStateKey: this.stateKey()
        });
      }
    }
  }, {
    key: "emptyLoadText",
    value: function emptyLoadText() {
      var noFilters = this.props.bank.filters === null;

      var noQuestions = function noQuestions() {
        return "Er zijn nog geen vragen in deze bank.";
      };

      var noResults = function noResults() {
        return "De zoekopdracht heeft geen resultaten opgeleverd.";
      };

      return noFilters ? noQuestions() : noResults();
    }
  }, {
    key: "render",
    value: function render() {
      return _react.default.createElement(_Page.default, null, this.renderModals(), this.renderNav(), _react.default.createElement("div", {
        className: styles.content
      }, this.renderName(), _react.default.createElement("div", {
        className: styles.topMenu
      }, this.renderTopLeftMenu(), this.renderTopRightMenu()), this.renderSearch(), _react.default.createElement(_PaginatedCollection.default, {
        empty: this.emptyLoadText(),
        params: this.props.search,
        getPage: this.getPageDebounced,
        renderRecords: this.renderRecords,
        stateKey: this.stateKey()
      })));
    }
  }]);
  Bank.displayName = "Bank";
  return Bank;
}(_react.Component), _class2.propTypes = {
  activeQuizId: _propTypes.default.string,
  addEntryToQuiz: _propTypes.default.func,
  bankId: _propTypes.default.string.isRequired,
  bank: _propTypes.default.instanceOf(_Bank.default).isRequired,
  useBankSearch: _propTypes.default.bool,
  closeTray: _propTypes.default.func.isRequired,
  getBank: _propTypes.default.func.isRequired,
  getBankEntries: _propTypes.default.func.isRequired,
  isCompact: _propTypes.default.bool,
  navigateToBanks: _propTypes.default.func.isRequired,
  // can be from consumer
  navigateToBankEntry: _propTypes.default.func.isRequired,
  // can be from consumer
  navigateToBuild: _propTypes.default.func,
  // from consumer
  onError: _propTypes.default.func,
  openModal: _propTypes.default.func.isRequired,
  position: _propTypes.default.number,
  resetSearch: _propTypes.default.func.isRequired,
  screenreaderNotification: _propTypes.default.func.isRequired,
  search: _reactImmutableProptypes.default.map.isRequired,
  stimulusId: _propTypes.default.string
}, _class2.defaultProps = {
  activeQuizId: null,
  addEntryToQuiz: null,
  useBankSearch: false,
  isCompact: false,
  minSearchRefreshInterval: 100,
  navigateToBuild: null,
  onError: null,
  position: 0,
  stimulusId: null
}, _temp)) || _class);
exports.default = Bank;