'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, _initialiseProps;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _immutable = require('immutable');

var immutable = _interopRequireWildcard(_immutable);

var _debounce = require('lodash/debounce');

var _debounce2 = _interopRequireDefault(_debounce);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _reactImmutableProptypes = require('react-immutable-proptypes');

var _reactImmutableProptypes2 = _interopRequireDefault(_reactImmutableProptypes);

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 _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 _debounceLatestPromise = require('../../../../common/util/debounceLatestPromise');

var _debounceLatestPromise2 = _interopRequireDefault(_debounceLatestPromise);

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

var _AddBankEntryModal2 = _interopRequireDefault(_AddBankEntryModal);

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

var _BankEntriesList2 = _interopRequireDefault(_BankEntriesList);

var _BankSearch = require('../../BankSearch');

var _BankSearch2 = _interopRequireDefault(_BankSearch);

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), _initialiseProps.call(_this), _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.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 _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: 'Opret bank-indtastning' },
            'Ny'
          )
        );
      }
    }
  }, {
    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: 'Tilf\xF8j denne bank til quiz' },
            'Alt / tilf\xE6ldigt'
          )
        );
      }
    }
  }, {
    key: 'stateKey',
    value: function stateKey() {
      return _constants.BANKS_BANK_ENTRY_PAGINATION + ':' + 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 _react2.default.createElement(_BankSearch2.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 'Der er endnu ingen sp\xF8rgsm\xE5l i denne bank.';
      };
      var noResults = function noResults() {
        return 'S\xF8gningen gav ingen resultater.';
      };
      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(),
            params: this.props.search,
            getPage: this.getPageDebounced,
            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,
  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,
  position: _propTypes2.default.number,
  resetSearch: _propTypes2.default.func.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  search: _reactImmutableProptypes2.default.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
}, _initialiseProps = function _initialiseProps() {
  var _this2 = this;

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

  this.renderHeaderMenu = function () {
    if (!_this2.props.isCompact) {
      return _react2.default.createElement(_HeaderMenu2.default, { bank: _this2.props.bank });
    }
  };

  this.storeCreateBankEntryButtonRef = function (c) {
    _this2.createBankEntryButton = c;
  };

  this.addBankToQuiz = function () {
    var newEntry = _QuizEntry2.default.create({
      entryId: _this2.props.bankId,
      entryType: 'Bank',
      position: _this2.props.position,
      stimulusQuizEntryId: _this2.props.stimulusId
    });
    _this2.props.addEntryToQuiz(_this2.props.activeQuizId, newEntry.entryId, newEntry.entryType, newEntry.getProperties(), false).then(function () {
      _this2.props.screenreaderNotification('Bank blev tilf\xF8jet til testen');
    });
  };

  this.renderTopLeftMenu = function () {
    return _react2.default.createElement(
      'div',
      { className: styles.topLeftMenu },
      _this2.renderMultiAdd()
    );
  };

  this.renderTopRightMenu = function () {
    return _react2.default.createElement(
      'div',
      { className: styles.topRightMenu },
      _this2.renderNewBankEntryButton()
    );
  };

  this.announceResults = (0, _debounce2.default)(function () {
    // 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
    _this2.props.screenreaderNotification('S\xF8geresultater klar');
  }, 1000);

  this.getPage = function (page, search) {
    var _props = _this2.props,
        getBankEntries = _props.getBankEntries,
        bankId = _props.bankId,
        useBankSearch = _props.useBankSearch;


    var text = search.get('text');
    var interactionTypes = search.get('interactionTypes', immutable.Set()).toJS();
    var tags = search.get('tags', immutable.Set()).toJS();
    var filters = { interactionTypes: interactionTypes, tags: tags };
    var params = { search: text, filters: filters };

    var resultPage = getBankEntries(bankId, useBankSearch, params);
    if (resultPage) {
      return resultPage.then(function (results) {
        _this2.announceResults();
        return results;
      });
    } else {
      return Promise.resolve(null);
    }
  };

  this.getPageDebounced = (0, _debounceLatestPromise2.default)(function () {
    return _this2.getPage.apply(_this2, arguments);
  }, 100);

  this.renderRecords = function (recordIds) {
    var addEntryFunc = _this2.props.isCompact && _this2.props.addEntryToQuiz || null;
    return _react2.default.createElement(_BankEntriesList2.default, {
      addEntryToQuiz: addEntryFunc,
      bankId: _this2.props.bankId,
      navigateToBankEntry: _this2.props.navigateToBankEntry,
      recordIds: recordIds
    });
  };
}, _temp2)) || _class);
exports.default = Bank;