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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

var _propTypes2 = _interopRequireDefault(_propTypes);

var _immutable = require('immutable');

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

var _NumberInput2 = _interopRequireDefault(_NumberInput);

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 _Setting = require('../Setting');

var _Setting2 = _interopRequireDefault(_Setting);

var _Errors = require('../../../../../../common/components/shared/errors/Errors');

var _Errors2 = _interopRequireDefault(_Errors);

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

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._3b3mEaIJZX29OXjV0xfNHT {\n  display: flex;\n  flex-direction: column;\n}\n\n._2JPDuHo4bHRxDmT0Wx11U1 {\n  display: flex;\n}\n\n._3xR8Oib3FiR-C_bUDWKck- {\n  display: inline-flex;\n  padding: 0 ' + theme.timeInputWrapperPadding + ';\n}\n\n._14GFlBaq0Vx4lAz6b32epB {\n  padding: ' + theme.timeInfoPadding + ' 0;\n}\n\n._2jBsxBXHnM4aeCNovEyAU {\n  padding: ' + theme.errorPadding + ';\n}\n';
  },
  'wrapper': '_3b3mEaIJZX29OXjV0xfNHT',
  'inputsWrapper': '_2JPDuHo4bHRxDmT0Wx11U1',
  'timeInputWrapper': '_3xR8Oib3FiR-C_bUDWKck-',
  'timeInfo': '_14GFlBaq0Vx4lAz6b32epB',
  'errors': '_2jBsxBXHnM4aeCNovEyAU'
};


var HOURS_LIMIT = 168;
var MINUTES_LIMIT = 90;
var LIMIT_IN_SECONDS = HOURS_LIMIT * _FormattedDuration.HOUR_IN_SECONDS;

function parseNumber(n) {
  return parseInt(n, 10) || 0;
}

var BuildingTimer = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp = _class2 = function (_Component) {
  (0, _inherits3.default)(BuildingTimer, _Component);

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

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

    _initialiseProps.call(_this);

    var _getHoursMinutesSecon = (0, _FormattedDuration.getHoursMinutesSeconds)(props.sessionTimeLimitInSeconds),
        hours = _getHoursMinutesSecon.hours,
        minutes = _getHoursMinutesSecon.minutes;

    _this.state = {
      hours: hours,
      minutes: minutes,
      errors: {
        hours: null,
        minutes: null
      }
    };
    return _this;
  }

  (0, _createClass3.default)(BuildingTimer, [{
    key: 'convertToSeconds',
    value: function convertToSeconds(hours, minutes) {
      return hours * _FormattedDuration.HOUR_IN_SECONDS + minutes * _FormattedDuration.MINUTE_IN_SECONDS;
    }
  }, {
    key: 'render',
    value: function render() {
      var hasTimeLimit = this.props.hasTimeLimit;

      return _react2.default.createElement(
        _Setting2.default,
        {
          automationData: 'sdk-timeLimit-toggle',
          isChecked: hasTimeLimit,
          label: (0, _formatMessage2.default)('Time limit'),
          onChange: this.toggleHasTimeLimit,
          showMore: hasTimeLimit
        },
        _react2.default.createElement(
          'div',
          { className: styles.wrapper },
          _react2.default.createElement(
            'div',
            { className: styles.inputsWrapper },
            _react2.default.createElement(
              'span',
              { className: styles.timeInputWrapper },
              _react2.default.createElement(_NumberInput2.default, {
                label: _react2.default.createElement(
                  _Text2.default,
                  { weight: 'light', color: 'secondary', size: 'small' },
                  (0, _formatMessage2.default)('Hours')
                ),
                inline: true,
                width: '5.5rem',
                value: this.state.hours,
                min: '0',
                onChange: this.handleHoursChange,
                'data-automation': 'sdk-timeLimit-hours'
              })
            ),
            _react2.default.createElement(
              'span',
              { className: styles.timeInputWrapper },
              _react2.default.createElement(_NumberInput2.default, {
                label: _react2.default.createElement(
                  _Text2.default,
                  { weight: 'light', color: 'secondary', size: 'small' },
                  (0, _formatMessage2.default)('Minutes')
                ),
                inline: true,
                width: '5.5rem',
                value: this.state.minutes,
                min: '0',
                onChange: this.handleMinutesChange,
                'data-automation': 'sdk-timeLimit-minutes'
              })
            )
          ),
          _react2.default.createElement(
            'div',
            { className: styles.errors },
            _react2.default.createElement(_Errors2.default, { errorList: this.state.errors.hours || (0, _immutable.List)() }),
            _react2.default.createElement(_Errors2.default, { errorList: this.state.errors.minutes || (0, _immutable.List)() })
          ),
          _react2.default.createElement(
            'div',
            { className: styles.timeInfo },
            _react2.default.createElement(
              _Text2.default,
              { weight: 'light', color: 'secondary', size: 'small' },
              (0, _formatMessage2.default)('Set to 0 for no time limit')
            )
          )
        )
      );
    }
  }]);
  BuildingTimer.displayName = 'BuildingTimer'
  ;
  return BuildingTimer;
}(_react.Component), _class2.propTypes = {
  setQuizHasTimeLimit: _propTypes2.default.func.isRequired,
  setSessionTimeLimitInSecondsUi: _propTypes2.default.func.isRequired,
  setSessionTimeLimitInSecondsApi: _propTypes2.default.func.isRequired,
  sessionTimeLimitInSeconds: _propTypes2.default.number,
  hasTimeLimit: _propTypes2.default.bool.isRequired,
  activeQuizId: _propTypes2.default.string.isRequired
}, _class2.defaultProps = {
  sessionTimeLimitInSeconds: 0
}, _initialiseProps = function _initialiseProps() {
  var _this2 = this;

  this.toggleHasTimeLimit = function (event) {
    var _props = _this2.props,
        setQuizHasTimeLimit = _props.setQuizHasTimeLimit,
        activeQuizId = _props.activeQuizId;

    var value = event.target.checked;
    setQuizHasTimeLimit(activeQuizId, value);
    _this2.setState({ errors: { minutes: null, hours: null } });
  };

  this.setNewLimit = function (hours, minutes) {
    var _props2 = _this2.props,
        setSessionTimeLimitInSecondsApi = _props2.setSessionTimeLimitInSecondsApi,
        setSessionTimeLimitInSecondsUi = _props2.setSessionTimeLimitInSecondsUi,
        activeQuizId = _props2.activeQuizId;

    var limitInSeconds = _this2.convertToSeconds(hours, minutes);
    setSessionTimeLimitInSecondsUi(activeQuizId, limitInSeconds);
    // make sure we have a valid limit before calling the api
    if (limitInSeconds <= LIMIT_IN_SECONDS && minutes <= MINUTES_LIMIT) {
      // TODO: debounce these updates
      setSessionTimeLimitInSecondsApi(activeQuizId, limitInSeconds);
    }
  };

  this.handleTimeChange = function (hours, minutes) {
    var hoursMsg = void 0,
        minutesMsg = void 0;
    if (hours > HOURS_LIMIT) {
      hoursMsg = (0, _formatMessage2.default)('{hours, number} hours exceeds maximum limit of {limit, number}.', { hours: hours, limit: HOURS_LIMIT });
    } else if (_this2.convertToSeconds(hours, minutes) > LIMIT_IN_SECONDS) {
      minutesMsg = (0, _formatMessage2.default)('{minutes, plural, one {# minute} other {# minutes}} will cause hours to exceed maximum hour limit of {limit, number}.', { minutes: minutes, limit: HOURS_LIMIT });
    }
    if (minutes > MINUTES_LIMIT) {
      minutesMsg = (0, _formatMessage2.default)('{minutes, number} minutes exceeds maximum limit of {limit, number}.', { minutes: minutes, limit: MINUTES_LIMIT });
    }
    _this2.setState({
      hours: hours,
      minutes: minutes,
      errors: { minutes: (0, _immutable.List)([minutesMsg]), hours: (0, _immutable.List)([hoursMsg]) }
    });
    _this2.setNewLimit(hours, minutes);
  };

  this.handleHoursChange = function (event, value, normalizedValue) {
    var hours = parseNumber(normalizedValue);
    var minutes = _this2.state.minutes;
    _this2.handleTimeChange(hours, minutes);
  };

  this.handleMinutesChange = function (event, value, normalizedValue) {
    var minutes = parseNumber(normalizedValue);
    var hours = _this2.state.hours;
    _this2.handleTimeChange(hours, minutes);
  };
}, _temp)) || _class);
exports.default = BuildingTimer;