'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,
    _default_enIE_number = Intl.NumberFormat('en-IE', { style: 'decimal' }).format;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

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

var _reactImmutableProptypes2 = _interopRequireDefault(_reactImmutableProptypes);

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

var _debounce2 = _interopRequireDefault(_debounce);

var _IconMoveUpTopLine = require('instructure-icons/lib/Line/IconMoveUpTopLine');

var _IconMoveUpTopLine2 = _interopRequireDefault(_IconMoveUpTopLine);

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

var _Button2 = _interopRequireDefault(_Button);

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

var _lib2 = _interopRequireDefault(_lib);

var _FormFieldGroup = require('@instructure/ui-forms/lib/components/FormFieldGroup');

var _FormFieldGroup2 = _interopRequireDefault(_FormFieldGroup);

var _ScreenReaderContent = require('@instructure/ui-a11y/lib/components/ScreenReaderContent');

var _ScreenReaderContent2 = _interopRequireDefault(_ScreenReaderContent);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

var _windowChecks = require('../../../../../common/util/windowChecks');

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

var _componentForItem = require('../../../../../common/util/componentForItem');

var _componentForItem2 = _interopRequireDefault(_componentForItem);

var _instUIMessages = require('../../../../../common/util/instUIMessages');

var _CustomPropTypes = require('../../../../../common/util/CustomPropTypes');

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

var _PositionBox = require('../../../../../common/components/resources/positionBox/PositionBox');

var _PositionBox2 = _interopRequireDefault(_PositionBox);

var _Pin = require('../../../../../common/components/Pin');

var _Pin2 = _interopRequireDefault(_Pin);

var _RceImageImportModal = require('../../../../../common/components/RichContentInput/RceImageImportModal');

var _RceImageImportModal2 = _interopRequireDefault(_RceImageImportModal);

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

var _theme2 = _interopRequireDefault(_theme);

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

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n:root {\n  --spacerHeight: 0.5rem;\n}\n\n.TakeItem__styles__wrapper {\n  padding: ' + theme.wrapperPadding + ' 0;\n}\n\n.TakeItem__styles__question_spacer {\n  height: ' + theme.spacerHeight + ';\n}\n\n.TakeItem__styles__question_spacer_line {\n  height: calc(' + theme.spacerHeight + ' / 2); /* make var w calc */\n}\n\n.TakeItem__styles__question {\n  width: 100%;\n  padding: ' + theme.questionPaddingTopBottom + ' ' + theme.questionPaddingLeftRight + ';\n  box-sizing: border-box;\n}\n\n.TakeItem__styles__header {\n  display: flex;\n  flex-direction: column;\n}\n\n.TakeItem__styles__headerSection {\n  display: flex;\n  flex-direction: row;\n  justify-content: space-between;\n}\n\n.TakeItem__styles__points {\n  flex: 1 1 auto;\n  display: flex;\n  flex-direction: row;\n  justify-content: flex-start;\n  align-items: center;\n  font-size: ' + theme.pointsFontSize + ';\n  color: ' + theme.pointsColor + ';\n}\n\nlegend {\n  border: none;\n  display: none;\n}\n\n.TakeItem__styles__contentWrapper {\n  margin-left: ' + theme.contentWrapperMargin + ';\n}\n';
  },
  'wrapper': 'TakeItem__styles__wrapper',
  'question_spacer': 'TakeItem__styles__question_spacer',
  'question_spacer_line': 'TakeItem__styles__question_spacer_line',
  'question': 'TakeItem__styles__question',
  'header': 'TakeItem__styles__header',
  'headerSection': 'TakeItem__styles__headerSection',
  'points': 'TakeItem__styles__points',
  'contentWrapper': 'TakeItem__styles__contentWrapper'
};
var TakeItem = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(TakeItem, _Component);

  function TakeItem() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = TakeItem.__proto__ || Object.getPrototypeOf(TakeItem)).call.apply(_ref, [this].concat(args))), _this), _this._editResponse = function (resp) {
      return _this.props.editResponse(_this.props.sessionItem, resp);
    }, _this._debouncedEditResponse = (0, _debounce2.default)(_this._editResponse, 500, {
      leading: false,
      maxWait: 1000,
      trailing: true
    }), _this.handleResponseUpdate = function (resp) {
      if (_this.props.timeIsUp) {
        _this.props.addError('Time is up. Answer not saved.');
      } else if (JSON.stringify(resp).length < _constants.TAKE_CHAR_LIMIT) {
        // Update in the UI
        _this.props.previewResponse(_this.props.sessionItem, resp);
        // Send back to kinesis
        _this._debouncedEditResponse(resp);
      }
    }, _this.getError = function (field) {
      var errors = _this.props.response.getErrors().toJS();
      return (0, _instUIMessages.toErrors)(errors[field] || []);
    }, _this.pinWithScreenreaderMessage = function () {
      var confirmationMessage = _this.props.isPinned ? 'Item unpinned' : 'Item pinned';
      return _this.props.pinSessionItem(_this.props.quizSessionId, _this.props.position).then(function () {
        return _this.props.screenreaderNotification(confirmationMessage);
      });
    }, _this.propsForInteraction = function () {
      var _this$props = _this.props,
          appContainer = _this$props.appContainer,
          item = _this$props.item,
          interactionFileUpload = _this$props.interactionFileUpload,
          openImportModal = _this$props.openImportModal,
          quizSessionId = _this$props.quizSessionId,
          response = _this$props.response,
          screenreaderNotification = _this$props.screenreaderNotification,
          sessionItem = _this$props.sessionItem;


      var simpleItem = item.toJS();
      var simpleUserResponse = response.userResponse && response.userResponse.toJS();
      var onUploadError = function onUploadError() {
        _this.props.addError('Your upload failed. Please try again.');
      };

      var mediaUpload = function mediaUpload(id, file, callback) {
        interactionFileUpload(_constants.PARENT_TYPE_QUIZ_SESSION, quizSessionId, file, callback, onUploadError);
      };

      return {
        // TODO - implement cancelMediaUpload
        appContainer: appContainer,
        handleResponseUpdate: _this.handleResponseUpdate,
        interactionData: simpleItem.interactionData,
        itemBody: simpleItem.itemBody,
        itemId: sessionItem.id,
        mediaUpload: mediaUpload,
        notifyScreenreader: screenreaderNotification,
        openImportModal: openImportModal,
        properties: simpleItem.properties,
        renderImportModal: _this.renderImportModal,
        scoringData: simpleItem.scoringData,
        userResponse: simpleUserResponse || {}
      };
    }, _this.renderImportModal = function (importModalId, onSuccess, onClose) {
      return _react2.default.createElement(_RceImageImportModal2.default, {
        importModalId: importModalId,
        onClose: onClose,
        onSuccess: onSuccess,
        parentType: _constants.PARENT_TYPE_QUIZ_SESSION,
        parentId: _this.props.quizSessionId
      });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(TakeItem, [{
    key: 'getPointsText',
    value: function getPointsText() {
      var _s, _n, _i, _v;

      return _s = this.props.pointsPossible, _n = +_s, (_i = Math.floor(Math.abs(+_s)), _v = (_s + '.').split('.')[1].length, _i === 1 && _v === 0 ? _default_enIE_number(this.props.pointsPossible) + ' point' : _default_enIE_number(this.props.pointsPossible) + ' points');
    }
  }, {
    key: 'renderJumpToInfoButton',
    value: function renderJumpToInfoButton() {
      if (this.props.scrollToInfo && (0, _windowChecks.onPhone)()) {
        return _react2.default.createElement(
          _Button2.default,
          { onClick: this.props.scrollToInfo, icon: _IconMoveUpTopLine2.default },
          _react2.default.createElement(
            _ScreenReaderContent2.default,
            null,
            'View Stimulus'
          )
        );
      }
    }
  }, {
    key: 'renderPin',
    value: function renderPin() {
      return _react2.default.createElement(_Pin2.default, {
        isPinned: this.props.isPinned,
        pinSessionItem: this.pinWithScreenreaderMessage,
        position: this.props.position
      });
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this._debouncedEditResponse.flush();
    }
  }, {
    key: 'render',
    value: function render() {
      var Interaction = (0, _componentForItem2.default)(this.props.interactionType.slug, _constants.COMPONENT_TAKE);
      var positionText = 'Item at position ' + _default_enIE_number(this.props.position);

      return _react2.default.createElement(
        'div',
        { className: styles.wrapper, tabIndex: '-1' },
        _react2.default.createElement(
          'div',
          { className: styles.question_spacer },
          _react2.default.createElement('div', { className: styles.question_spacer_line })
        ),
        _react2.default.createElement(
          'article',
          { className: styles.question },
          _react2.default.createElement(
            'header',
            { className: styles.header },
            _react2.default.createElement(
              'section',
              { className: styles.headerSection },
              _react2.default.createElement(_PositionBox2.default, { position: this.props.position, headingText: positionText }),
              _react2.default.createElement(
                'div',
                { className: styles.points },
                this.getPointsText()
              ),
              _react2.default.createElement(
                'div',
                null,
                this.props.showPin && this.renderPin()
              ),
              this.renderJumpToInfoButton()
            )
          ),
          _react2.default.createElement(
            'div',
            { className: styles.contentWrapper },
            _react2.default.createElement(
              _FormFieldGroup2.default,
              { messages: this.getError('userResponse') },
              _react2.default.createElement(Interaction, this.propsForInteraction())
            )
          )
        )
      );
    }
  }]);
  TakeItem.displayName = 'TakeItem'
  ;
  return TakeItem;
}(_react.Component), _class2.propTypes = {
  addError: _propTypes2.default.func.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  editResponse: _propTypes2.default.func.isRequired,
  interactionFileUpload: _propTypes2.default.func.isRequired,
  interactionType: _propTypes2.default.object.isRequired, // eslint-disable-line
  isPinned: _propTypes2.default.bool.isRequired,
  item: _reactImmutableProptypes2.default.record.isRequired,
  openImportModal: _propTypes2.default.func.isRequired,
  pinSessionItem: _propTypes2.default.func.isRequired,
  pointsPossible: _propTypes2.default.number.isRequired,
  position: _propTypes2.default.number.isRequired,
  previewResponse: _propTypes2.default.func.isRequired,
  quizSessionId: _propTypes2.default.string.isRequired,
  response: _reactImmutableProptypes2.default.record.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  scrollToInfo: _propTypes2.default.func,
  sessionItem: _reactImmutableProptypes2.default.record.isRequired,
  showPin: _propTypes2.default.bool.isRequired,
  timeIsUp: _propTypes2.default.bool.isRequired
}, _class2.defaultProps = {
  scrollToInfo: null
}, _temp2)) || _class);
exports.default = TakeItem;