'use strict';

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

var _regenerator = require('babel-runtime/regenerator');

var _regenerator2 = _interopRequireDefault(_regenerator);

var _asyncToGenerator2 = require('babel-runtime/helpers/asyncToGenerator');

var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);

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_nb_number = Intl.NumberFormat('nb', { 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 _omit = require('lodash/omit');

var _omit2 = _interopRequireDefault(_omit);

var _url = require('url');

var _url2 = _interopRequireDefault(_url);

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

var _Button2 = _interopRequireDefault(_Button);

var _Checkbox = require('@instructure/ui-forms/lib/components/Checkbox');

var _Checkbox2 = _interopRequireDefault(_Checkbox);

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 _lib = require('@instructure/ui-themeable/lib');

var _lib2 = _interopRequireDefault(_lib);

var _Card = require('../../../../common/components/shared/Card');

var _Card2 = _interopRequireDefault(_Card);

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

var _Page2 = _interopRequireDefault(_Page);

var _Spinner = require('../../../../common/components/shared/spinner/Spinner');

var _Spinner2 = _interopRequireDefault(_Spinner);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var _SessionItemResultList = require('../../resources/sessionItemResult/SessionItemResultList');

var _SessionItemResultList2 = _interopRequireDefault(_SessionItemResultList);

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.Grading__styles__root {\n  display: flex;\n  flex-direction: column;\n  background-color: ' + theme.rootBackgroundColor + ';\n}\n\n.Grading__styles__submitBar {\n  width: 90%;\n  margin: ' + theme.submitBarMargin + ';\n  margin-bottom: ' + theme.submitBarMarginBottom + ';\n\n  display: flex;\n  justify-content: flex-end;\n  align-self: center;\n  align-items: center;\n}\n\n.Grading__styles__continueToNextStudentWrapper {\n  margin-right: 2rem;\n}\n\n.Grading__styles__fudgePointsSection {\n  width: 90%;\n  justify-content: space-between;\n  background-color: ' + theme.fudgePointsSectionBackgroundColor + ';\n  border-radius: ' + theme.fudgePointsSectionBorderRadius + ';\n  margin: ' + theme.fudgePointsSectionMargin + ';\n  padding: ' + theme.fudgePointsSectionPadding + ';\n\n  flex: 1 1 auto;\n  display: flex;\n  align-items: center;\n  align-self: center;\n}\n\n.Grading__styles__fudgePointsBox {\n  flex: 0 0 5rem;\n  width: ' + theme.fudgePointsBoxWidth + ';\n  padding: ' + theme.fudgePointsBoxPadding + ';\n  margin: ' + theme.fudgePointsBoxMargin + ';\n}\n\n.Grading__styles__fudgePointsLabel {\n  font-size: ' + theme.fudgePointsLabelFontSize + ';\n  font-weight: ' + theme.fudgePointsLabelFontWeight + ';\n}\n\n.Grading__styles__fudgeInfo {\n  flex: 1 1 auto;\n  font-size: ' + theme.fudgeInfoFontSize + ';\n}\n\n.Grading__styles__finalScoreWrapper {\n  width: 90%;\n  margin: ' + theme.finalScoreWrapperMargin + ';\n  padding: ' + theme.finalScoreWrapperPadding + ';\n\n  display: flex;\n  justify-content: space-between;\n  align-items: center;\n  align-self: center;\n}\n\n.Grading__styles__finalScoreLabel {\n  flex: 1 1 auto;\n  font-size: ' + theme.finalScoreLabelFontSize + ';\n  width: 90%;\n}\n\n.Grading__styles__finalScore {\n  flex: 1 1 5rem;\n  text-align: end;\n  font-size: ' + theme.finalScoreFontSize + ';\n  font-weight: ' + theme.finalScoreFontWeight + ';\n}\n\n[dir="ltr"] .Grading__styles__finalScore {\n  text-align: right;\n}\n\n[dir="rtl"] .Grading__styles__finalScore {\n  text-align: left;\n}\n';
  },
  'root': 'Grading__styles__root',
  'submitBar': 'Grading__styles__submitBar',
  'continueToNextStudentWrapper': 'Grading__styles__continueToNextStudentWrapper',
  'fudgePointsSection': 'Grading__styles__fudgePointsSection',
  'fudgePointsBox': 'Grading__styles__fudgePointsBox',
  'fudgePointsLabel': 'Grading__styles__fudgePointsLabel',
  'fudgeInfo': 'Grading__styles__fudgeInfo',
  'finalScoreWrapper': 'Grading__styles__finalScoreWrapper',
  'finalScoreLabel': 'Grading__styles__finalScoreLabel',
  'finalScore': 'Grading__styles__finalScore'
};
var Grading = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(Grading, _Component);

  function Grading() {
    var _ref,
        _this2 = this;

    var _temp, _this, _ret;

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

    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 = Grading.__proto__ || Object.getPrototypeOf(Grading)).call.apply(_ref, [this].concat(args))), _this), _this.changeQuizSessionResponseHandler = function (event) {
      var messageData = event.data;
      if (!messageData || messageData.subject !== _constants.SUBMISSION_CHANGE_SUBJECT) {
        return;
      }

      // submission.external_tool_url signature comes from canvas
      var externalToolUrl = messageData.submission && messageData.submission.external_tool_url;
      if (externalToolUrl) {
        var urlParams = _url2.default.parse(externalToolUrl, true) || { query: {} };
        var participantSessionId = urlParams.query.participant_session_id;
        if (participantSessionId) {
          _this.changeUser(participantSessionId);
        }
      }
    }, _this.handleChangePoints = function (sessionItemResultKey, itemId, newPoints) {
      _this.props.sessionItemResultsModification(sessionItemResultKey, {
        itemId: itemId,
        score: newPoints,
        id: sessionItemResultKey
      });
    }, _this.handleChangeFeedback = function (sessionItemResultKey, itemId, feedback) {
      _this.props.sessionItemResultsModification(sessionItemResultKey, {
        itemId: itemId,
        feedback: feedback,
        id: sessionItemResultKey
      });
    }, _this.handleChangeGradeStatus = function (sessionItemResultKey, itemId, newStatus) {
      var clearCorrect = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;

      var scoredData = { gradeStatus: newStatus };
      if (clearCorrect) {
        scoredData.correct = null;
      }
      // FIXME: should this be a visible alert?
      _this.props.screenreaderNotification('merket som ' + newStatus);
      _this.props.sessionItemResultsModification(sessionItemResultKey, {
        itemId: itemId,
        id: sessionItemResultKey,
        scoredData: scoredData
      });
    }, _this.handleChangeFudgePoints = function (event, fudgePoints, normalizedFudgePoints) {
      _this.setState({ fudgePoints: fudgePoints, normalizedFudgePoints: normalizedFudgePoints });
    }, _this.handleBlurFudgePoints = function () {
      if (_this.state.normalizedFudgePoints != null) {
        var fudgePoints = parseFloat(_this.state.normalizedFudgePoints) || 0;
        _this.props.changeFudgePoints(_this.props.quizSessionResult.id, fudgePoints);
      }
    }, _this.handleUpdateResults = function () {
      var _this$props = _this.props,
          quizSessionId = _this$props.quizSessionId,
          postQuizSessionResults = _this$props.postQuizSessionResults,
          sessionItems = _this$props.sessionItems,
          workingQuizSessionResult = _this$props.workingQuizSessionResult,
          afterGradeUpdate = _this$props.afterGradeUpdate;

      var mods = sessionItems.map(function (sessionItem) {
        return sessionItem.sessionItemResult.getWorkingInstance();
      });
      // replace graderId at some point as well
      var alteredMods = mods.map(function (m) {
        return (0, _omit2.default)(m, 'gradingMethod');
      });
      var workingFudgePoints = workingQuizSessionResult.fudgePoints;

      return _this.withUpdatingGrade(postQuizSessionResults(quizSessionId, alteredMods, workingFudgePoints)).then(function () {
        _this.postGradeRefresh();
        _this.props.successNotification('Sluttresultatet er oppdatert.');
        return afterGradeUpdate(quizSessionId, _this.continueToNextStudent && _this.continueToNextStudent.checked);
      });
    }, _this.withUpdatingGrade = function () {
      var _ref2 = (0, _asyncToGenerator3.default)( /*#__PURE__*/_regenerator2.default.mark(function _callee(promise) {
        return _regenerator2.default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!_this.props.updatingGrade) {
                  _context.next = 2;
                  break;
                }

                throw new Error('Grade update in progress');

              case 2:
                _this.props.setUpdatingGrade(true);
                _context.prev = 3;
                _context.next = 6;
                return promise;

              case 6:
                return _context.abrupt('return', _context.sent);

              case 7:
                _context.prev = 7;

                _this.props.setUpdatingGrade(false);
                return _context.finish(7);

              case 10:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, _this2, [[3,, 7, 10]]);
      }));

      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }(), _this.postGradeRefresh = function () {
      var window = _this.props.windowObj;
      if (window.parent !== window) {
        window.parent.postMessage('refreshGrades', '*');
      }
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }
  // ===========
  //   CONFIG
  // ===========

  (0, _createClass3.default)(Grading, [{
    key: 'componentWillMount',


    // =============
    //   LIFECYCLE
    // =============

    value: function componentWillMount() {
      this.props.postToParent({ subject: _constants.REGISTER_MESSAGE_SUBJECT });
      this.fetchData();
      this.props.windowObj.addEventListener('message', this.changeQuizSessionResponseHandler);
      this.loadFudgePoints(this.props.workingQuizSessionResult);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.loadFudgePoints(nextProps.workingQuizSessionResult);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.props.windowObj.removeEventListener('message', this.changeQuizSessionResponseHandler);
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate(prevProps) {
      if (prevProps.quizSessionId !== this.props.quizSessionId) {
        this.fetchData();
      }
    }
  }, {
    key: 'loadFudgePoints',
    value: function loadFudgePoints(workingQuizSessionResult) {
      var fudgePoints = workingQuizSessionResult.fudgePoints;

      this.setState({
        fudgePoints: Number(fudgePoints),
        normalizedFudgePoints: fudgePoints
      });
    }
  }, {
    key: 'changeUser',
    value: function changeUser(participantSessionId) {
      this.props.onChangeUser(participantSessionId); // Trigger consumer provided callback
    }
  }, {
    key: 'fetchData',
    value: function fetchData() {
      var _props = this.props,
          fetchQuizSession = _props.fetchQuizSession,
          quizSessionId = _props.quizSessionId;

      fetchQuizSession(quizSessionId);
    }

    // =============
    //   CALLBACKS
    // =============

  }, {
    key: 'points',
    value: function points() {
      var quizSessionResult = this.props.quizSessionResult;

      return quizSessionResult && quizSessionResult.score;
    }
  }, {
    key: 'pointsPossible',
    value: function pointsPossible() {
      var quizSessionResult = this.props.quizSessionResult;

      return quizSessionResult && quizSessionResult.pointsPossible;
    }
  }, {
    key: 'renderFudgePoints',


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

    value: function renderFudgePoints() {
      if (!this.props.showFudgePoints) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        { className: styles.fudgePointsSection },
        _react2.default.createElement(
          'div',
          { className: styles.fudgeInfo },
          _react2.default.createElement(
            'div',
            { className: styles.fudgePointsLabel },
            'Poengjustering'
          ),
          _react2.default.createElement(
            'div',
            null,
            'Juster poengsum manuelt ved \xE5 legge til positive eller negative poeng i denne boksen'
          )
        ),
        _react2.default.createElement(
          'div',
          { className: styles.fudgePointsBox },
          _react2.default.createElement(_NumberInput2.default, {
            name: 'fudgePointsInput',
            placeholder: '--',
            label: _react2.default.createElement(
              _ScreenReaderContent2.default,
              null,
              'Poengjustering'
            ),
            onChange: this.handleChangeFudgePoints,
            onBlur: this.handleBlurFudgePoints,
            value: this.state.fudgePoints,
            'data-automation': 'sdk-fudge-points-numberinput',
            width: '5rem'
          })
        )
      );
    }
  }, {
    key: 'renderUpdateButton',
    value: function renderUpdateButton() {
      var _this3 = this;

      var continueToNextStudentCheckbox = void 0;
      if (this.props.showContinueToNextStudentCheckbox) {
        continueToNextStudentCheckbox = _react2.default.createElement(
          'span',
          { className: styles.continueToNextStudentWrapper },
          _react2.default.createElement(_Checkbox2.default, {
            inline: true,
            label: 'Fortsett til neste student',
            ref: function ref(_ref3) {
              _this3.continueToNextStudent = _ref3;
            },
            defaultChecked: true,
            'data-automation': 'sdk-continue-to-next-student-checkbox'
          })
        );
      }

      return _react2.default.createElement(
        'div',
        { className: styles.submitBar },
        continueToNextStudentCheckbox,
        _react2.default.createElement(
          _Button2.default,
          {
            disabled: this.props.updatingGrade || !this.props.hasResultsModifications,
            variant: 'primary',
            onClick: this.handleUpdateResults,
            'data-automation': 'sdk-update-grade-button'
          },
          'Oppdater'
        )
      );
    }
  }, {
    key: 'renderFinalScore',
    value: function renderFinalScore() {
      return _react2.default.createElement(
        'div',
        { className: styles.finalScoreWrapper },
        _react2.default.createElement(
          'div',
          { className: styles.finalScoreLabel },
          'Sluttkarakter'
        ),
        _react2.default.createElement(
          'div',
          { className: styles.finalScore, 'data-automation': 'sdk-final-score-div' },
          _default_nb_number(this.points()) + ' / ' + _default_nb_number(this.pointsPossible())
        )
      );
    }
  }, {
    key: 'render',
    value: function render() {
      var _props2 = this.props,
          needToLoad = _props2.needToLoad,
          sessionItems = _props2.sessionItems,
          header = _props2.header;


      if (needToLoad) {
        return _react2.default.createElement(
          _Card2.default,
          { wrapped: true },
          _react2.default.createElement(_Spinner2.default, null)
        );
      }

      return _react2.default.createElement(
        _Page2.default,
        null,
        _react2.default.createElement(
          _Card2.default,
          { wrapped: true, className: styles.root, 'data-automation': 'sdk-grading' },
          header,
          _react2.default.createElement(_SessionItemResultList2.default, {
            handleChangePoints: this.handleChangePoints,
            handleChangeFeedback: this.handleChangeFeedback,
            handleChangeGradeStatus: this.handleChangeGradeStatus,
            quizSessionId: this.props.quizSessionId,
            regradingIdentifier: this.props.regradingIdentifier,
            sessionItems: sessionItems
          }),
          this.renderFudgePoints(),
          this.renderFinalScore(),
          this.renderUpdateButton()
        )
      );
    }
  }]);
  Grading.displayName = 'Grading'
  ;
  return Grading;
}(_react.Component), _class2.propTypes = {
  afterGradeUpdate: _propTypes2.default.func,
  changeFudgePoints: _propTypes2.default.func.isRequired,
  fetchQuizSession: _propTypes2.default.func.isRequired,
  hasResultsModifications: _propTypes2.default.bool.isRequired,
  header: _propTypes2.default.node,
  needToLoad: _propTypes2.default.bool.isRequired,
  onChangeUser: _propTypes2.default.func,
  postQuizSessionResults: _propTypes2.default.func.isRequired,
  postToParent: _propTypes2.default.func.isRequired,
  quizSessionId: _propTypes2.default.string.isRequired,
  quizSessionResult: _reactImmutableProptypes2.default.record.isRequired,
  regradingIdentifier: _propTypes2.default.string.isRequired,
  screenreaderNotification: _propTypes2.default.func.isRequired,
  sessionItemResultsModification: _propTypes2.default.func.isRequired,
  sessionItems: _reactImmutableProptypes2.default.list.isRequired,
  setUpdatingGrade: _propTypes2.default.func.isRequired,
  showContinueToNextStudentCheckbox: _propTypes2.default.bool,
  showFudgePoints: _propTypes2.default.bool,
  successNotification: _propTypes2.default.func.isRequired,
  updatingGrade: _propTypes2.default.bool,
  windowObj: _propTypes2.default.shape({
    addEventListener: _propTypes2.default.func,
    removeEventListener: _propTypes2.default.func
  }),
  workingQuizSessionResult: _reactImmutableProptypes2.default.record.isRequired
}, _class2.defaultProps = {
  afterGradeUpdate: function afterGradeUpdate() {},

  header: null,
  onChangeUser: function onChangeUser() {},

  showContinueToNextStudentCheckbox: false,
  showFudgePoints: true,
  updatingGrade: false,
  windowObj: window }, _temp2)) || _class);
exports.default = Grading;