"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

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

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));

var _getPrototypeOf3 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _uiFormField = require("@instructure/ui-form-field");

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

var _uiLayout = require("@instructure/ui-layout");

var _quizNumberInput = _interopRequireDefault(require("@instructure/quiz-number-input"));

var _FormattedDuration = require("../../../../../common/components/shared/FormattedDuration");

var _formatMessage = _interopRequireDefault(require("@instructure/quiz-i18n/lib/format-message"));

var _default_fr_number = Intl.NumberFormat("fr", { style: "decimal" }).format;

var shouldNormalizeOnChange = function shouldNormalizeOnChange(e) {
  // Input events from arrow keys or arrow buttons should be normalized immediately
  var fromButtonInput = e.nativeEvent.target && e.nativeEvent.target.tagName !== 'INPUT';
  var fromArrowKeys = e.key === 'ArrowUp' || e.key === 'ArrowDown';
  return fromButtonInput || fromArrowKeys;
};

var ExtraHoursMinutes =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(ExtraHoursMinutes, _Component);

  function ExtraHoursMinutes() {
    var _getPrototypeOf2;

    var _this;

    (0, _classCallCheck2.default)(this, ExtraHoursMinutes);

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

    _this = (0, _possibleConstructorReturn2.default)(this, (_getPrototypeOf2 = (0, _getPrototypeOf3.default)(ExtraHoursMinutes)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _this.onChangeTime = function (e, rawString, inputNumber, source) {
      var normalizeOnChange = shouldNormalizeOnChange(e);
      var minutes = source === 'minutes' ? inputNumber : _this.state.minutes;
      minutes = normalizeOnChange ? minutes : Math.max(minutes, 0);
      var hours = source === 'hours' ? inputNumber : _this.state.hours;
      var totalSeconds = minutes * _FormattedDuration.MINUTE_IN_SECONDS + hours * _FormattedDuration.HOUR_IN_SECONDS;
      var hoursMessages = null;

      if (totalSeconds > _this.props.maxTimeInSeconds) {
        var units = (0, _FormattedDuration.getHoursMinutesSeconds)(totalSeconds);
        var newHours = units.hours;
        var newMinutes = units.minutes;
        var maxTime = (0, _FormattedDuration.getHoursMinutesSeconds)(_this.props.maxTimeInSeconds);
        var maxHours = maxTime.hours;
        var maxMinutes = maxTime.minutes;
        var hoursMsgText = _default_fr_number(newHours) + " hrs " + _default_fr_number(newMinutes) + " mins exceeds maximum time of " + _default_fr_number(maxHours) + " hrs " + _default_fr_number(maxMinutes) + " mins.";
        hoursMessages = [{
          type: 'error',
          text: hoursMsgText
        }];
        totalSeconds = _this.props.maxTimeInSeconds;
      }

      if (normalizeOnChange) {
        _this.setState({
          hours: hours,
          minutes: minutes,
          hoursMessages: hoursMessages,
          minutesMessages: null,
          totalSeconds: totalSeconds
        }, _this.onNormalizeTime);
      } else {
        _this.setState({
          hours: hours,
          rawHoursText: hours,
          minutes: minutes,
          rawMinutesText: minutes,
          hoursMessages: hoursMessages,
          minutesMessages: null,
          totalSeconds: totalSeconds
        });
      }
    };

    _this.onNormalizeTime = function () {
      var units = (0, _FormattedDuration.getHoursMinutesSeconds)(_this.state.totalSeconds);
      var newHours = units.hours;
      var newMinutes = units.minutes;

      _this.setState({
        hours: newHours,
        rawHoursText: newHours,
        minutes: newMinutes,
        rawMinutesText: newMinutes
      });

      _this.props.onChange(_this.state.totalSeconds);
    };

    _this.onChangeExtraMinutes = function (e, rawString, normalizedString) {
      // Check that input is a valid number.
      // If not, set an error indicator. If so, remove error indicator.
      var inputNumber = normalizedString === null ? NaN : Number(normalizedString);
      var numberInvalid = isNaN(inputNumber);
      var rawStringBlank = rawString === '';

      if (numberInvalid) {
        var _params;

        var minutesMessageText = _formatMessage.default.custom(["userInput", "string"], "fr", rawString, _params) + " is not a valid number.";

        _this.setState({
          rawMinutesText: rawString,
          minutesMessages: rawStringBlank ? null : [{
            type: 'error',
            text: minutesMessageText
          }]
        });
      } else {
        _this.onChangeTime(e, rawString, inputNumber, 'minutes');
      }
    };

    _this.onChangeExtraHours = function (e, rawString, normalizedString) {
      var inputNumber = normalizedString === null ? NaN : Number(normalizedString);
      var numberInvalid = isNaN(inputNumber);
      var rawStringBlank = rawString === '';

      if (numberInvalid) {
        var _params2;

        var hoursMessageText = _formatMessage.default.custom(["userInput", "string"], "fr", rawString, _params2) + " is not a valid number.";

        _this.setState({
          rawHoursText: rawString,
          hoursMessages: rawStringBlank ? null : [{
            type: 'error',
            text: hoursMessageText
          }]
        });
      } else {
        _this.onChangeTime(e, rawString, inputNumber, 'hours');
      }
    };

    _this.render = function () {
      return _react.default.createElement(_uiLayout.View, {
        display: "block",
        margin: "medium none"
      }, _react.default.createElement(_uiFormField.FormFieldGroup, {
        description: _react.default.createElement(_ScreenReaderContent.default, null, "Additional time"),
        layout: "columns",
        vAlign: "top",
        startAt: "small"
      }, _react.default.createElement(_quizNumberInput.default, {
        label: "Heures",
        min: 0,
        value: _this.state.rawHoursText,
        onChange: _this.onChangeExtraHours,
        onBlur: _this.onNormalizeTime,
        messages: _this.state.hoursMessages
      }), _react.default.createElement(_quizNumberInput.default, {
        label: "Minutes",
        value: _this.state.rawMinutesText,
        onChange: _this.onChangeExtraMinutes,
        onBlur: _this.onNormalizeTime,
        messages: _this.state.minutesMessages
      })));
    };

    return _this;
  }

  (0, _createClass2.default)(ExtraHoursMinutes, [{
    key: "componentWillMount",
    value: function componentWillMount() {
      var _getHoursMinutesSecon = (0, _FormattedDuration.getHoursMinutesSeconds)(this.props.extraTimeInSeconds),
          hours = _getHoursMinutesSecon.hours,
          minutes = _getHoursMinutesSecon.minutes;

      this.setState({
        hours: hours,
        minutes: minutes,
        rawHoursText: hours,
        rawMinutesText: minutes,
        totalSeconds: this.props.extraTimeInSeconds
      });
    }
  }]);
  return ExtraHoursMinutes;
}(_react.Component);

ExtraHoursMinutes.propTypes = {
  onChange: _propTypes.default.func.isRequired,
  extraTimeInSeconds: _propTypes.default.number,
  maxTimeInSeconds: _propTypes.default.number.isRequired
};
ExtraHoursMinutes.defaultProps = {
  extraTimeInSeconds: 0
};
var _default = ExtraHoursMinutes;
exports.default = _default;