'use strict';

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

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

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;

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 _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _defer = require('lodash/defer');

var _defer2 = _interopRequireDefault(_defer);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

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

var _lib2 = _interopRequireDefault(_lib);

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

var _theme2 = _interopRequireDefault(_theme);

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

var _Errors2 = _interopRequireDefault(_Errors);

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

var _formatMessage2 = _interopRequireDefault(_formatMessage);

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

var styles = {
  template: function template(theme) {
    return '/*  imported from styles.css  */\n\n._3v-cKJrFGKjD0jtatpzHWe {\n  position: relative;\n  width: 100%;\n  height: 5rem;\n\n  border-bottom: solid;\n  border-width: ' + theme.titleEditWrapperBorderWidth + ';\n  border-color: ' + theme.titleEditWrapperBorderColor + ';\n  box-sizing: border-box;\n\n  padding-left: ' + theme.titleEditWrapperLeftPadding + ';\n\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n}\n\n._10gCspLXruFpnk25JIMu9g {\n  font-size: ' + theme.titleEditInputFontSize + ';\n  width: 80%;\n}\n\n._1oWVHYp7rBkodriumlGqRo,\n._1Cb3kxlOyg-2LDfjClNOVG {\n  width: 100%;\n  flex: 1 1 auto;\n\n  display: flex;\n  flex-direction: column;\n  justify-content: center;\n}\n\n._1ca199gaCr_aQeyF8eEPHA {\n  margin: ' + theme.errorBorderMargin + ';\n  padding: ' + theme.errorBorderPadding + ';\n  border: solid 1px ' + theme.errorBorderColor + ';\n  border-radius: ' + theme.errorBorderBorderRadius + ';\n}\n';
  },
  'titleEditWrapper': '_3v-cKJrFGKjD0jtatpzHWe',
  'titleEditInput': '_10gCspLXruFpnk25JIMu9g',
  'inputWrapper': '_1oWVHYp7rBkodriumlGqRo',
  'errorsWrapper': '_1Cb3kxlOyg-2LDfjClNOVG',
  'errorBorder': '_1ca199gaCr_aQeyF8eEPHA'
};


// =================================

// once editing is toggled this div
// is rendered & has actions that
// allow for canceling

// =================================

var TitleEdit = exports.TitleEdit = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(TitleEdit, _Component);

  function TitleEdit() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = TitleEdit.__proto__ || Object.getPrototypeOf(TitleEdit)).call.apply(_ref, [this].concat(args))), _this), _this.defer = function (fn) {
      // to enable syncronous testing
      var deferFn = _this.props.deferMock || _defer2.default;
      deferFn(fn);
    }, _this.switchOffEditing = function () {
      _this.ifValidElseError(function () {
        _this.defer(function () {
          // make sure they have actually left the component
          if (document.activeElement !== _this.cancelButton && document.activeElement !== _this.input) {
            _this.props.saveAndPreview();
          }
        });
      });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(TitleEdit, [{
    key: 'componentDidMount',


    // todo: extract this into a shared method
    // to be used on many components
    value: function componentDidMount() {
      var input = _reactDom2.default.findDOMNode(this.input);
      // some browsers add chars so * 2 to ensure at end
      var valLength = input.value.length * 2;
      input.focus();
      input.setSelectionRange(valLength, valLength);
    }
  }, {
    key: 'ifValidElseError',
    value: function ifValidElseError(cb) {
      if (this.props.isValid) {
        this.props.hideError();
        cb();
      } else {
        this.props.showError();
      }
    }
  }, {
    key: 'setRef',
    value: function setRef(key) {
      var _this2 = this;

      return function (node) {
        _this2[key] = node;
      };
    }
  }, {
    key: 'hasErrors',
    value: function hasErrors() {
      return this.props.errorsAreShowing && this.props.errors.size > 0;
    }
  }, {
    key: 'renderErrors',
    value: function renderErrors() {
      if (this.hasErrors()) {
        return _react2.default.createElement(
          'div',
          { className: styles.errorsWrapper },
          _react2.default.createElement(_Errors2.default, { errorList: this.props.errors })
        );
      }
    }
  }, {
    key: 'inputClasses',
    value: function inputClasses() {
      var _classNames;

      return (0, _classnames2.default)((_classNames = {}, (0, _defineProperty3.default)(_classNames, styles.titleEditInput, true), (0, _defineProperty3.default)(_classNames, styles.errorBorder, this.hasErrors()), _classNames));
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        { ref: this.setRef('wrapper'), className: styles.titleEditWrapper, onBlur: this.switchOffEditing },
        _react2.default.createElement(
          'div',
          { className: styles.inputWrapper },
          _react2.default.createElement('input', {
            ref: this.setRef('input'),
            type: 'text',
            'aria-label': (0, _formatMessage2.default)('title'),
            placeholder: (0, _formatMessage2.default)('Add a Title...'),
            value: this.props.value,
            onKeyDown: this.props.onInputKeyDown,
            onChange: this.props.onInputChange,
            className: this.inputClasses()
          })
        ),
        this.renderErrors()
      );
    }
  }]);
  TitleEdit.displayName = 'TitleEdit'
  ;
  return TitleEdit;
}(_react.Component), _class2.propTypes = {
  value: _propTypes2.default.string.isRequired,
  isValid: _propTypes2.default.bool.isRequired,
  showError: _propTypes2.default.func.isRequired,
  hideError: _propTypes2.default.func.isRequired,
  errors: _reactImmutableProptypes2.default.list.isRequired,
  errorsAreShowing: _propTypes2.default.bool,
  onInputChange: _propTypes2.default.func.isRequired,
  onInputKeyDown: _propTypes2.default.func.isRequired,
  saveAndPreview: _propTypes2.default.func.isRequired,
  deferMock: _propTypes2.default.func
}, _class2.defaultProps = {
  errorsAreShowing: false,
  deferMock: _defer2.default }, _temp2)) || _class);
exports.default = TitleEdit;