'use strict';

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

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _dec, _class, _class2, _temp2;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _immutable = require('immutable');

var _most = require('most');

var most = _interopRequireWildcard(_most);

var _eventemitter = require('eventemitter3');

var _eventemitter2 = _interopRequireDefault(_eventemitter);

var _IconPlusLine = require('instructure-icons/lib/Line/IconPlusLine');

var _IconPlusLine2 = _interopRequireDefault(_IconPlusLine);

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

var _BreadcrumbLink2 = _interopRequireDefault(_BreadcrumbLink);

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

var _Button2 = _interopRequireDefault(_Button);

var _TextInput = require('@instructure/ui-forms/lib/components/TextInput');

var _TextInput2 = _interopRequireDefault(_TextInput);

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

var _Heading2 = _interopRequireDefault(_Heading);

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

var _AccessibleContent2 = _interopRequireDefault(_AccessibleContent);

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

var _lib2 = _interopRequireDefault(_lib);

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

var _Bank2 = _interopRequireDefault(_Bank);

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

var _Page2 = _interopRequireDefault(_Page);

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

var _PaginatedCollection2 = _interopRequireDefault(_PaginatedCollection);

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

var _QuizEntry2 = _interopRequireDefault(_QuizEntry);

var _formatMessage = require('../../../../common/format-message');

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _Spinner = require('@instructure/ui-elements/lib/components/Spinner');

var _Spinner2 = _interopRequireDefault(_Spinner);

var _AddBankEntryModal = require('../../AddBankEntryModal');

var _AddBankEntryModal2 = _interopRequireDefault(_AddBankEntryModal);

var _BankEntriesList = require('../../BankEntriesList');

var _BankEntriesList2 = _interopRequireDefault(_BankEntriesList);

var _HeaderMenu = require('../../HeaderMenu');

var _HeaderMenu2 = _interopRequireDefault(_HeaderMenu);

var _NavWrapper = require('../NavWrapper');

var _NavWrapper2 = _interopRequireDefault(_NavWrapper);

var _constants = require('../../../../constants');

var _theme = require('./theme');

var _theme2 = _interopRequireDefault(_theme);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n.Bank__styles__content {\n  padding: ' + theme.contentPaddingTopBottom + ' ' + theme.contentPaddingLeftRight + ';\n  background-color: ' + theme.contentBackgroundColor + ';\n}\n\n.Bank__styles__topMenu,\n.Bank__styles__topLeftMenu,\n.Bank__styles__topRightMenu {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n}\n\n.Bank__styles__topLeftMenu {\n  flex: 50%;\n}\n\n.Bank__styles__topRightMenu {\n  justify-content: flex-end;\n  flex: 50%;\n}\n\n.Bank__styles__bankName {\n  padding: 0 ' + theme.bankNamePaddingLeftRight + ' ' + theme.bankNamePaddingBottom + ' ' + theme.bankNamePaddingLeftRight + ';\n}\n\n.Bank__styles__searchBar {\n  display: flex;\n  flex-direction: row;\n}\n\n.Bank__styles__loading {\n  width: 2rem;\n  padding-top: 0.25rem;\n}\n\n@media screen and (--phoneBreakPoint) {\n  .Bank__styles__content {\n    padding: ' + theme.phoneContentPadding + ' 0;\n  }\n}\n';
  },
  'content': 'Bank__styles__content',
  'topMenu': 'Bank__styles__topMenu',
  'topLeftMenu': 'Bank__styles__topLeftMenu',
  'topRightMenu': 'Bank__styles__topRightMenu',
  'bankName': 'Bank__styles__bankName',
  'searchBar': 'Bank__styles__searchBar',
  'loading': 'Bank__styles__loading'
};
var Bank = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(Bank, _Component);

  function Bank() {
    var _ref;

    var _temp, _this, _ret;

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

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

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3.default)(this, (_ref = Bank.__proto__ || Object.getPrototypeOf(Bank)).call.apply(_ref, [this].concat(args))), _this), _this.state = { search: '' }, _this.openAddBankEntryModal = function () {
      _this.props.openModal(_constants.ADD_BANK_ENTRY_MODAL, {
        modalTrigger: _this.createBankEntryButton
      });
    }, _this.renderHeaderMenu = function () {
      if (!_this.props.isCompact) {
        return _react2.default.createElement(_HeaderMenu2.default, { bank: _this.props.bank });
      }
    }, _this.storeCreateBankEntryButtonRef = function (c) {
      _this.createBankEntryButton = c;
    }, _this.addBankToQuiz = function () {
      var newEntry = _QuizEntry2.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('El banco se agreg\xF3 con \xE9xito a la evaluaci\xF3n');
      });
    }, _this.renderTopLeftMenu = function () {
      return _react2.default.createElement(
        'div',
        { className: styles.topLeftMenu },
        _this.renderMultiAdd()
      );
    }, _this.renderTopRightMenu = function () {
      return _react2.default.createElement(
        'div',
        { className: styles.topRightMenu },
        _this.renderNewBankEntryButton()
      );
    }, _this.getPage = function (page) {
      var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
          search = _ref2.search;

      var _this$props = _this.props,
          getBankEntries = _this$props.getBankEntries,
          bankId = _this$props.bankId,
          useBankSearch = _this$props.useBankSearch;

      return getBankEntries(bankId, useBankSearch, { page: page, text: search });
    }, _this.renderRecords = function (recordIds) {
      var addEntryFunc = _this.props.isCompact && _this.props.addEntryToQuiz || null;
      return _react2.default.createElement(_BankEntriesList2.default, {
        addEntryToQuiz: addEntryFunc,
        bankId: _this.props.bankId,
        navigateToBankEntry: _this.props.navigateToBankEntry,
        recordIds: recordIds
      });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(Bank, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _this2 = this;

      if (this.props.onError) {
        this.props.getBank(this.props.bankId).catch(this.props.onError);
      } else {
        this.props.getBank(this.props.bankId);
      }

      var searchKey = Bank.searchKey(this.props);
      var search = new _eventemitter2.default();
      var minSearchRefreshInterval = this.props.minSearchRefreshInterval;

      // The code below uses most.js for transforming a stream of text input events
      // into the desired stream of page reset operations.

      this.onSearchUpdate = function (_ref3) {
        var value = _ref3.target.value;
        return search.emit('update', value);
      };
      this.searchStream = most.fromEvent('update', search)
      // immediately update the search bar with the new data
      .tap(function (text) {
        return _this2.props.mergeUI(searchKey, (0, _immutable.fromJS)({ text: text }));
      })
      // debounce requests so we don't overload the server
      .debounce(minSearchRefreshInterval).map(function (search) {
        _this2.props.mergeUI(searchKey, (0, _immutable.fromJS)({ loading: true }));
        return most.fromPromise(_this2.fetchPage(search));
      })
      // if the user types additional text while a query is in flight, we want
      // to ignore the old results when they arrive
      .switchLatest().multicast();

      this.displayResults();
    }
  }, {
    key: 'displayResults',
    value: function displayResults() {
      var _this3 = this;

      var searchKey = Bank.searchKey(this.props);

      // Visually reset the page when results arrive
      this.searchStream.observe(function (page) {
        _this3.props.mergeUI(searchKey, (0, _immutable.fromJS)({ loading: false }));
        _this3.resetPages(page);
      });

      // 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.searchStream.debounce(2000).observe(function () {
        return _this3.props.screenreaderNotification('Search results ready');
      });
    }
  }, {
    key: 'renderNav',
    value: function renderNav() {
      return _react2.default.createElement(
        _NavWrapper2.default,
        {
          closeTray: this.props.closeTray,
          navigateToBanks: this.props.navigateToBanks,
          navigateToBuild: this.props.navigateToBuild,
          renderHeaderMenu: this.renderHeaderMenu
        },
        _react2.default.createElement(
          _BreadcrumbLink2.default,
          { key: 'bank' },
          this.props.bank.title
        )
      );
    }
  }, {
    key: 'renderName',
    value: function renderName() {
      return _react2.default.createElement(
        'div',
        { className: styles.bankName },
        _react2.default.createElement(
          _Heading2.default,
          { level: 'h1' },
          this.props.bank.title
        )
      );
    }
  }, {
    key: 'renderAddBankEntryModal',
    value: function renderAddBankEntryModal() {
      if (!this.props.isCompact) {
        return _react2.default.createElement(_AddBankEntryModal2.default, {
          bankId: this.props.bankId,
          navigateToBankEntry: this.props.navigateToBankEntry
        });
      }
    }
  }, {
    key: 'renderModals',
    value: function renderModals() {
      return _react2.default.createElement(
        'div',
        null,
        this.renderAddBankEntryModal()
      );
    }
  }, {
    key: 'renderNewBankEntryButton',
    value: function renderNewBankEntryButton() {
      if (!this.props.isCompact) {
        return _react2.default.createElement(
          _Button2.default,
          {
            margin: 'small',
            ref: this.storeCreateBankEntryButtonRef,
            variant: 'primary',
            onClick: this.openAddBankEntryModal,
            'data-automation': 'sdk-new-bank-entry-button',
            icon: _IconPlusLine2.default
          },
          _react2.default.createElement(
            _AccessibleContent2.default,
            { alt: 'Crear una entrada en el banco' },
            'Nuevo'
          )
        );
      }
    }
  }, {
    key: 'renderMultiAdd',
    value: function renderMultiAdd() {
      var isEmpty = this.props.bank.itemEntryCount === 0;
      if (this.props.isCompact && !isEmpty) {
        return _react2.default.createElement(
          _Button2.default,
          { onClick: this.addBankToQuiz, margin: 'small', icon: _IconPlusLine2.default },
          _react2.default.createElement(
            _AccessibleContent2.default,
            { alt: 'Agregar este banco a la evaluaci\xF3n' },
            'Todos/aleatorio'
          )
        );
      }
    }
  }, {
    key: 'stateKey',
    value: function stateKey() {
      return _constants.BANKS_BANK_ENTRY_PAGINATION + ':' + this.props.bankId;
    }
  }, {
    key: 'fetchPage',
    value: function fetchPage(search) {
      return this.getPage(1, { search: search });
    }
  }, {
    key: 'resetPages',
    value: function resetPages(_ref4) {
      var records = _ref4.records,
          totalPages = _ref4.totalPages;

      this.props.setUI(this.stateKey(), (0, _immutable.fromJS)({
        contents: { 1: records },
        current: 1,
        total: totalPages
      }));
    }
  }, {
    key: 'renderLoading',
    value: function renderLoading() {
      if (this.props.search.get('loading') === true) {
        return _react2.default.createElement(
          'div',
          { className: styles.loading },
          _react2.default.createElement(_Spinner2.default, { size: 'x-small' })
        );
      }
    }
  }, {
    key: 'renderSearch',
    value: function renderSearch() {
      if (this.props.bank.filters !== null && this.props.useBankSearch) {
        return _react2.default.createElement(
          'div',
          { className: styles.searchBar },
          _react2.default.createElement(_TextInput2.default, {
            type: 'search',
            placeholder: 'Search',
            onChange: this.onSearchUpdate,
            value: this.props.search.get('text', '')
          }),
          this.renderLoading()
        );
      }
    }
  }, {
    key: 'emptyLoadText',
    value: function emptyLoadText() {
      var noFilters = this.props.bank.filters === null;
      var noQuestions = function noQuestions() {
        return 'No hay preguntas en este banco a\xFAn.';
      };
      var noResults = function noResults() {
        return 'The search returned no results.';
      };
      return noFilters ? noQuestions() : noResults();
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Page2.default,
        null,
        this.renderModals(),
        this.renderNav(),
        _react2.default.createElement(
          'div',
          { className: styles.content },
          this.renderName(),
          _react2.default.createElement(
            'div',
            { className: styles.topMenu },
            this.renderTopLeftMenu(),
            this.renderTopRightMenu()
          ),
          this.renderSearch(),
          _react2.default.createElement(_PaginatedCollection2.default, {
            empty: this.emptyLoadText(),
            getPage: this.getPage,
            renderRecords: this.renderRecords,
            stateKey: this.stateKey()
          })
        )
      );
    }
  }]);
  Bank.displayName = 'Bank'
  ;
  return Bank;
}(_react.Component), _class2.propTypes = {
  activeQuizId: _propTypes2.default.string,
  addEntryToQuiz: _propTypes2.default.func,
  bankId: _propTypes2.default.string.isRequired,
  bank: _propTypes2.default.instanceOf(_Bank2.default).isRequired,
  useBankSearch: _propTypes2.default.bool,
  closeTray: _propTypes2.default.func.isRequired,
  getBank: _propTypes2.default.func.isRequired,
  getBankEntries: _propTypes2.default.func.isRequired,
  isCompact: _propTypes2.default.bool,
  minSearchRefreshInterval: _propTypes2.default.number,
  navigateToBanks: _propTypes2.default.func.isRequired, // can be from consumer
  navigateToBankEntry: _propTypes2.default.func.isRequired, // can be from consumer
  navigateToBuild: _propTypes2.default.func, // from consumer
  onError: _propTypes2.default.func,
  openModal: _propTypes2.default.func.isRequired,
  setUI: _propTypes2.default.func.isRequired,
  mergeUI: _propTypes2.default.func.isRequired,
  position: _propTypes2.default.number,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  search: _propTypes2.default.instanceOf(Map).isRequired,
  stimulusId: _propTypes2.default.string
}, _class2.defaultProps = {
  activeQuizId: null,
  addEntryToQuiz: null,
  useBankSearch: false,
  isCompact: false,
  minSearchRefreshInterval: 100,
  navigateToBuild: null,
  onError: null,
  position: 0,
  stimulusId: null
}, _class2.searchKey = function (_ref5) {
  var bankId = _ref5.bankId;
  return _constants.BANKS_SEARCH_KEY + ':' + bankId;
}, _temp2)) || _class);
exports.default = Bank;