'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,
    _temp,
    _initialiseProps,
    _default_nl_number = Intl.NumberFormat('nl', { 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 _immutable = require('immutable');

var _react3 = require('format-message/react');

var _IconCheckLine = require('instructure-icons/lib/Line/IconCheckLine');

var _IconCheckLine2 = _interopRequireDefault(_IconCheckLine);

var _IconDiscussionLine = require('instructure-icons/lib/Line/IconDiscussionLine');

var _IconDiscussionLine2 = _interopRequireDefault(_IconDiscussionLine);

var _IconDiscussionSolid = require('instructure-icons/lib/Solid/IconDiscussionSolid');

var _IconDiscussionSolid2 = _interopRequireDefault(_IconDiscussionSolid);

var _IconXLine = require('instructure-icons/lib/Line/IconXLine');

var _IconXLine2 = _interopRequireDefault(_IconXLine);

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

var _Button2 = _interopRequireDefault(_Button);

var _NumberInput = require('@instructure/ui-forms/lib/components/NumberInput');

var _NumberInput2 = _interopRequireDefault(_NumberInput);

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

var _ScreenReaderContent2 = _interopRequireDefault(_ScreenReaderContent);

var _Text = require('@instructure/ui-elements/lib/components/Text');

var _Text2 = _interopRequireDefault(_Text);

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

var _lib2 = _interopRequireDefault(_lib);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var _CustomPropTypes2 = _interopRequireDefault(_CustomPropTypes);

var _IfFeature = require('../../../../../common/components/shared/IfFeature');

var _IfFeature2 = _interopRequireDefault(_IfFeature);

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

var _RichContentInput2 = _interopRequireDefault(_RichContentInput);

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.GradingBar__styles__root {\n  border-top: ' + theme.rootBorderWidth + ' solid ' + theme.rootBorderColor + ';\n  margin: 0 ' + theme.rootMargin + ';\n  display: flex;\n  align-items: center;\n}\n\n.GradingBar__styles__editFeedback {\n  margin: 0 ' + theme.editFeedbackMargin + ';\n}\n\n.GradingBar__styles__editFeedbackButtons {\n  display: flex;\n  justify-content: flex-end;\n}\n\n.GradingBar__styles__points {\n  width: ' + theme.pointsWidth + ';\n  padding: ' + theme.pointsPadding + ';\n  margin: ' + theme.pointsMargin + ';\n}\n\n.GradingBar__styles__pointsSection {\n  flex: 1 1 auto;\n  display: flex;\n  align-items: center;\n  justify-content: flex-end;\n  padding: 0 ' + theme.pointsSectionPadding + ';\n}\n\n.GradingBar__styles__regradeParent {\n  display: flex;\n  align-items: center;\n}\n\n.GradingBar__styles__originalScore {\n  display: flex;\n  align-items: center;\n}\n\n.GradingBar__styles__regradetext {\n  display: flex;\n  align-items: center;\n}\n\n.GradingBar__styles__divider {\n  margin: ' + theme.dividerMargin + ';\n}\n\n.GradingBar__styles__defaultNumberInput {\n  display: flex;\n  align-items: center;\n}\n\n.GradingBar__styles__pointsPossible {\n  margin-left: ' + theme.pointsPossibleMargin + ';\n}\n';
  },
  'root': 'GradingBar__styles__root',
  'editFeedback': 'GradingBar__styles__editFeedback',
  'editFeedbackButtons': 'GradingBar__styles__editFeedbackButtons',
  'points': 'GradingBar__styles__points',
  'pointsSection': 'GradingBar__styles__pointsSection',
  'regradeParent': 'GradingBar__styles__regradeParent',
  'originalScore': 'GradingBar__styles__originalScore',
  'regradetext': 'GradingBar__styles__regradetext',
  'divider': 'GradingBar__styles__divider',
  'defaultNumberInput': 'GradingBar__styles__defaultNumberInput',
  'pointsPossible': 'GradingBar__styles__pointsPossible'
};
var GradingBar = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp = _class2 = function (_Component) {
  (0, _inherits3.default)(GradingBar, _Component);

  function GradingBar(props) {
    (0, _classCallCheck3.default)(this, GradingBar);

    var _this = (0, _possibleConstructorReturn3.default)(this, (GradingBar.__proto__ || Object.getPrototypeOf(GradingBar)).call(this, props));

    _initialiseProps.call(_this);

    var points = _this.props.sessionItemResult.getWorkingInstance().score;
    if (typeof points == 'number' || typeof points == 'string') {
      points = Number(points);
    } else {
      points = null;
    }
    _this.state = {
      points: points,
      normalizedPoints: points
    };
    return _this;
  }

  // =============
  //   EXTERNALLY USED UTILS
  // =============

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

      return _s = pointsPossible, _n = +_s, (_i = Math.floor(Math.abs(+_s)), _v = (_s + '.').split('.')[1].length, _i === 1 && _v === 0 ? _default_nl_number(pointsPossible) + ' punt' : _default_nl_number(pointsPossible) + ' punten');
    }
  }, {
    key: 'getGradeStatus',
    value: function getGradeStatus() {
      var resultMods = this.props.itemResultsModifications || (0, _immutable.Map)();
      var workingGradeStatus = resultMods.getIn(['scoredData', 'gradeStatus']);
      if (workingGradeStatus) {
        return workingGradeStatus;
      }
      return this.props.sessionItemResult.getIn(['scoredData', 'gradeStatus']);
    }

    // =============
    //   HANDLERS
    // =============

  }, {
    key: 'renderSubjectiveButtons',


    // =============
    //   RENDERING
    // =============

    value: function renderSubjectiveButtons() {
      if (this.props.isSubjective) {
        var correctVariant = this.getGradeStatus() === 'correct' ? 'success' : 'light';
        var correctText = this.getGradeStatus() === 'correct' ? 'juist aan/uit uitgeschakeld' : 'juist aan/uit ingeschakeld';
        var incorrectVariant = this.getGradeStatus() === 'incorrect' ? 'danger' : 'light';
        var incorrectText = this.getGradeStatus() === 'incorrect' ? 'onjuist aan/uit uitgeschakeld' : 'onjuist aan/uit ingeschakeld';
        return _react2.default.createElement(
          'div',
          null,
          _react2.default.createElement(
            _Button2.default,
            {
              variant: correctVariant,
              onClick: this.handleStatusCorrectToggle,
              icon: _IconCheckLine2.default
            },
            _react2.default.createElement(
              _ScreenReaderContent2.default,
              null,
              correctText
            )
          ),
          _react2.default.createElement(
            _Button2.default,
            {
              variant: incorrectVariant,
              margin: '0 xx-small',
              onClick: this.handleStatusIncorrectToggle,
              icon: _IconXLine2.default
            },
            _react2.default.createElement(
              _ScreenReaderContent2.default,
              null,
              incorrectText
            )
          )
        );
      }
    }
  }, {
    key: 'renderFeedbackSection',
    value: function renderFeedbackSection() {
      var workingSessionItemResult = this.props.sessionItemResult.getWorkingInstance();
      var graderFeedbackContent = workingSessionItemResult.getIn(['feedback', 'graderFeedback', 'content'], '');
      var icon = graderFeedbackContent ? _IconDiscussionSolid2.default : _IconDiscussionLine2.default;

      return _react2.default.createElement(
        _Button2.default,
        {
          ref: this.handleFeedbackButtonRef,
          variant: 'icon',
          onClick: this.props.startFeedbackEdit,
          icon: icon
        },
        _react2.default.createElement(
          _ScreenReaderContent2.default,
          null,
          'Feedback revisorniveau bewerken'
        )
      );
    }
  }, {
    key: 'renderRegradeInfo',
    value: function renderRegradeInfo() {
      var _s2, _n2, _i2, _v2;

      return _react2.default.createElement(
        'div',
        { className: styles.regradeParent },
        _react2.default.createElement(
          'div',
          { className: styles.originalScore },
          _react2.default.createElement(
            _Text2.default,
            { color: 'secondary' },
            'Vorige score ' + (_s2 = this.regradeInfo.get('originalPointsPossible'), _n2 = +_s2, (_i2 = Math.floor(Math.abs(+_s2)), _v2 = (_s2 + '.').split('.')[1].length, _i2 === 1 && _v2 === 0 ? _default_nl_number(this.regradeInfo.get('originalScore')) + ' / ' + _default_nl_number(this.regradeInfo.get('originalPointsPossible')) + ' punt' : _default_nl_number(this.regradeInfo.get('originalScore')) + ' / ' + _default_nl_number(this.regradeInfo.get('originalPointsPossible')) + ' punten'))
          ),
          _react2.default.createElement(
            'div',
            { className: styles.divider },
            _react2.default.createElement(
              _Text2.default,
              { color: 'secondary' },
              '|'
            )
          )
        ),
        _react2.default.createElement(
          'div',
          { className: styles.regradeText },
          _react2.default.createElement(
            _Text2.default,
            { color: 'warning' },
            'Score herberekenen:'
          )
        ),
        this.renderNumberInput(),
        _react2.default.createElement(
          _Text2.default,
          { color: 'warning' },
          '/ ',
          this.pointsPossibleDescription(this.regradeInfo.get('newPointsPossible'))
        )
      );
    }
  }, {
    key: 'renderNumberInput',
    value: function renderNumberInput() {
      return _react2.default.createElement(
        'div',
        { className: styles.points },
        _react2.default.createElement(_NumberInput2.default, {
          placeholder: '--',
          label: _react2.default.createElement(
            _ScreenReaderContent2.default,
            null,
            'Score bewerken'
          ),
          onChange: this.handleChangePoints,
          onBlur: this.handleBlurPoints,
          value: this.state.points,
          width: '5rem',
          'data-automation': 'sdk-grading-edit-score-input'
        })
      );
    }
  }, {
    key: 'renderDefaultNumberInput',
    value: function renderDefaultNumberInput() {
      return _react2.default.createElement(
        'div',
        { className: styles.defaultNumberInput },
        this.renderNumberInput(),
        _react2.default.createElement(
          'span',
          { className: styles.pointsPossible },
          '/ ',
          this.pointsPossibleDescription(this.props.sessionItem.pointsPossible)
        )
      );
    }
  }, {
    key: 'renderRegradeButton',
    value: function renderRegradeButton() {
      if (this.props.isAutogradeable) {
        return _react2.default.createElement(
          _IfFeature2.default,
          { name: 'regrading_from_speedgrader' },
          _react2.default.createElement(
            'div',
            null,
            _react2.default.createElement(
              _Button2.default,
              {
                margin: '0 small',
                onClick: this.props.regradeToggleAction,
                ref: this.handleRegradeButtonRef,
                'data-automation': 'sdk-regrade-request-button'
              },
              (0, _react3.formatChildren)('Item <0>herbeoordelen ' + _default_nl_number(this.props.sessionItem.position) + '</0>', [_react2.default.createElement(_ScreenReaderContent2.default, { key: '0' })])
            )
          )
        );
      }
    }
  }, {
    key: 'renderEditGraderFeedback',
    value: function renderEditGraderFeedback() {
      if (!this.props.isEditing) {
        return;
      }

      return _react2.default.createElement(
        'div',
        { className: styles.editFeedback },
        _react2.default.createElement(
          'label',
          { htmlFor: 'edit_grader_feedback' },
          'Extra opmerkingen'
        ),
        _react2.default.createElement(_RichContentInput2.default, {
          appContainer: this.props.appContainer,
          defaultContent: this.props.graderFeedback.get('content'),
          onKeyUp: this.props.updateFeedbackEdit,
          onChange: this.props.updateFeedbackEdit,
          ref: this.handleRCERef,
          textareaId: 'edit_grader_feedback_' + this.props.sessionItem.id,
          uploadPath: '/api/quiz_sessions/' + this.props.activeQuizSessionId + '/session_item_results/media_upload_url'
        }),
        _react2.default.createElement(
          'div',
          { className: styles.editFeedbackButtons },
          _react2.default.createElement(
            _Button2.default,
            {
              size: 'small',
              margin: 'x-small',
              onClick: this.props.cancelFeedbackEdit
            },
            'Annuleren'
          ),
          _react2.default.createElement(
            _Button2.default,
            {
              variant: 'primary',
              size: 'small',
              margin: 'x-small',
              onClick: this.props.submitFeedbackEdit
            },
            'Gereed'
          )
        )
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var isRegraded = this.regradeInfo && this.regradeInfo.get('regraded');

      return _react2.default.createElement(
        'div',
        null,
        this.renderEditGraderFeedback(),
        _react2.default.createElement(
          'div',
          { className: styles.root },
          _react2.default.createElement(
            'div',
            null,
            this.renderFeedbackSection()
          ),
          this.renderRegradeButton(),
          _react2.default.createElement(
            'div',
            { className: styles.pointsSection },
            this.renderSubjectiveButtons(),
            isRegraded ? this.renderRegradeInfo() : this.renderDefaultNumberInput()
          )
        )
      );
    }
  }, {
    key: 'regradeInfo',


    // =============
    //   INTERNAL UTILS
    // =============

    get: function get() {
      return this.props.sessionItemResult.regradeInfo;
    }
  }]);
  GradingBar.displayName = 'GradingBar'
  ;
  return GradingBar;
}(_react.Component), _class2.propTypes = {
  activeQuizSessionId: _propTypes2.default.string.isRequired,
  appContainer: _CustomPropTypes2.default.selectors.isRequired,
  graderFeedback: _reactImmutableProptypes2.default.map.isRequired,
  handleChangeGradeStatus: _propTypes2.default.func.isRequired,
  handleChangePoints: _propTypes2.default.func.isRequired,
  isAutogradeable: _propTypes2.default.bool.isRequired,
  isEditing: _propTypes2.default.bool.isRequired,
  isSubjective: _propTypes2.default.bool.isRequired,
  itemResultsModifications: _reactImmutableProptypes2.default.map.isRequired,
  regradeToggleAction: _propTypes2.default.func.isRequired,
  sessionItem: _reactImmutableProptypes2.default.record.isRequired,
  sessionItemResult: _reactImmutableProptypes2.default.record.isRequired,
  startFeedbackEdit: _propTypes2.default.func.isRequired,
  submitFeedbackEdit: _propTypes2.default.func.isRequired,
  updateFeedbackEdit: _propTypes2.default.func.isRequired,
  cancelFeedbackEdit: _propTypes2.default.func.isRequired
}, _initialiseProps = function _initialiseProps() {
  var _this2 = this;

  this.regradeButtonRef = null;
  this.feedbackButtonRef = null;
  this.rceRef = null;
  this._timeouts = [];

  this.focusRegradeButton = function () {
    _this2.regradeButtonRef && _this2.regradeButtonRef.focus();
  };

  this.focusFeedbackButton = function () {
    _this2.feedbackButtonRef && _this2.feedbackButtonRef.focus();
  };

  this.focusRce = function (event) {
    _this2.rceRef && _this2.rceRef.wrappedInstance.focus();
  };

  this.handleChangePoints = function (event, points, normalizedPoints) {
    _this2.setState({ points: points, normalizedPoints: normalizedPoints });
    var gradeStatus = _this2.getGradeStatus();
    if (!gradeStatus || gradeStatus === 'waiting') {
      _this2.props.handleChangeGradeStatus('graded');
    }
  };

  this.handleBlurPoints = function () {
    var points = parseFloat(_this2.state.normalizedPoints) || 0;
    _this2.setState({ points: points, normalizedPoints: points });
    _this2.props.handleChangePoints(points);
  };

  this.handleStatusCorrectToggle = function () {
    var newPoints = +_this2.props.sessionItem.pointsPossible;
    _this2.props.handleChangePoints(newPoints);
    _this2.setState({ points: '' + newPoints });
    var newStatus = _this2.getGradeStatus() === 'correct' ? 'graded' : 'correct';
    _this2.props.handleChangeGradeStatus(newStatus, newStatus === 'graded');
  };

  this.handleStatusIncorrectToggle = function () {
    _this2.props.handleChangePoints(0);
    _this2.setState({ points: '0' });
    var newStatus = _this2.getGradeStatus() === 'incorrect' ? 'graded' : 'incorrect';
    _this2.props.handleChangeGradeStatus(newStatus, newStatus === 'graded');
  };

  this.handleRegradeButtonRef = function (node) {
    _this2.regradeButtonRef = node;
  };

  this.handleFeedbackButtonRef = function (node) {
    _this2.feedbackButtonRef = node;
  };

  this.handleRCERef = function (node) {
    _this2.rceRef = node;
  };
}, _temp)) || _class);
exports.default = GradingBar;