'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, _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 _Alert = require('@instructure/ui-alerts/lib/components/Alert');

var _Alert2 = _interopRequireDefault(_Alert);

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

var _Button2 = _interopRequireDefault(_Button);

var _CloseButton = require('@instructure/ui-buttons/lib/components/CloseButton');

var _CloseButton2 = _interopRequireDefault(_CloseButton);

var _Heading = require('@instructure/ui-elements/lib/components/Heading');

var _Heading2 = _interopRequireDefault(_Heading);

var _Progress = require('@instructure/ui-elements/lib/components/Progress');

var _Progress2 = _interopRequireDefault(_Progress);

var _TabList = require('@instructure/ui-tabs/lib/components/TabList');

var _TabList2 = _interopRequireDefault(_TabList);

var _ToggleDetails = require('@instructure/ui-toggle-details/lib/components/ToggleDetails');

var _ToggleDetails2 = _interopRequireDefault(_ToggleDetails);

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

var _Text2 = _interopRequireDefault(_Text);

var _TextInput = require('@instructure/ui-forms/lib/components/TextInput');

var _TextInput2 = _interopRequireDefault(_TextInput);

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

var _lib2 = _interopRequireDefault(_lib);

var _alertHelpers = require('../../../common/util/alertHelpers');

var _Modal = require('../../../common/components/Modal');

var _Modal2 = _interopRequireDefault(_Modal);

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

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

var _theme2 = _interopRequireDefault(_theme);

var _ImportFileSelector = require('./ImportFileSelector');

var _ImportFileSelector2 = _interopRequireDefault(_ImportFileSelector);

var _formatMessage = require('../../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.ImportModal__styles__altTextWrapper {\n  margin-top: ' + theme.altTextMargin + ';\n}\n';
  },
  'altTextWrapper': 'ImportModal__styles__altTextWrapper'
};
var ImportModal = (_dec = (0, _lib2.default)(_theme2.default, styles), _dec(_class = (_temp2 = _class2 = function (_Component) {
  (0, _inherits3.default)(ImportModal, _Component);

  function ImportModal() {
    var _ref;

    var _temp, _this, _ret;

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

    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 = ImportModal.__proto__ || Object.getPrototypeOf(ImportModal)).call.apply(_ref, [this].concat(args))), _this), _this.state = { selectedTabIndex: 0 }, _this.componentDidUpdate = function (prevProps, prevState) {
      if (!_this.props.modalOpen) {
        return;
      }
      var _this$props = _this.props,
          disableConfirm = _this$props.disableConfirm,
          uploadStatus = _this$props.uploadStatus;

      var isUploadSuccess = uploadStatus === _constants.FILE_UPLOAD_SUCCESS && uploadStatus !== prevProps.uploadStatus;
      if (disableConfirm && isUploadSuccess) {
        _this.continueAction();
      }
    }, _this.cancelAction = function () {
      _this.props.clearFiles();
      _this.props.clearAltText();
      if (_this.props.closeOverride) {
        // this timeout is needed because if this modal closes first,
        // then the ItemFeedbackModal will also close in the same click
        // since it will think the click happened "onOverlayClick"
        setTimeout(_this.props.closeOverride);
      } else {
        _this.props.closeModal();
      }
      // Wait for the modal to close before setting the status to prevent flashing
      // the select screen when closing the modal due to the modal having a gradual
      // fade transition that will display the change in state
      setTimeout(function () {
        return _this.props.setUploadStatus(_constants.FILE_UPLOAD_SELECT);
      }, 300);
    }, _this.errorAction = function () {
      return _this.props.setUploadStatus(_constants.FILE_UPLOAD_ERROR);
    }, _this.continueAction = function () {
      var uploadStatus = _this.props.uploadStatus;

      switch (uploadStatus) {
        case _constants.FILE_UPLOAD_SUCCESS:
        case _constants.FILE_UPLOAD_FAILURE:
          _this.cancelAction();
          break;
        case _constants.FILE_UPLOAD_ERROR:
          _this.props.clearFiles();
          _this.props.clearAltText();
          _this.props.setUploadStatus(_constants.FILE_UPLOAD_SELECT);
          break;
        default:
          _this.props.fileUpload(_this.props.files.get(0), _this.errorAction, _this.props.altText);
          _this.props.setUploadStatus(_constants.FILE_UPLOAD_IMPORTING);
          _this.props.onContinue();
          break;
      }
    }, _this.handleFile = function (file) {
      _this.props.receiveFile(file);
      _this.confirmButton.focus();
    }, _this.onAltTextChange = function (e) {
      _this.props.setAltText(e.target.value);
    }, _this.handleTabChange = function (newTabIndex) {
      _this.setState({ selectedTabIndex: newTabIndex });
    }, _temp), (0, _possibleConstructorReturn3.default)(_this, _ret);
  }

  (0, _createClass3.default)(ImportModal, [{
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      if (this.props.uploadStatus === _constants.FILE_UPLOAD_SUCCESS && this.props.modalOpen) {
        this.cancelAction();
      }
    }
  }, {
    key: 'setRef',
    value: function setRef(refName) {
      var _this2 = this;

      return function (node) {
        _this2[refName] = node;
      };
    }
  }, {
    key: 'disableCancelButton',
    value: function disableCancelButton() {
      var uploadStatus = this.props.uploadStatus;

      return [_constants.FILE_UPLOAD_ERROR, _constants.FILE_UPLOAD_FAILURE, _constants.FILE_UPLOAD_SUCCESS].includes(uploadStatus);
    }
  }, {
    key: 'cancelButton',
    value: function cancelButton() {
      return _react2.default.createElement(
        _Button2.default,
        {
          disabled: this.disableCancelButton(),
          onClick: this.cancelAction,
          margin: _constants.XSMALL_SIDE_MARGIN,
          ref: this.setRef('cancelImportButton'),
          'data-automation': 'sdk-cancel-import-button'
        },
        'Annuler'
      );
    }
  }, {
    key: 'disableContinueButton',
    value: function disableContinueButton() {
      var _props = this.props,
          uploadStatus = _props.uploadStatus,
          files = _props.files;

      return uploadStatus === _constants.FILE_UPLOAD_IMPORTING || files.size === 0;
    }
  }, {
    key: 'continueButtonMessage',
    value: function continueButtonMessage() {
      var uploadStatus = this.props.uploadStatus;

      switch (uploadStatus) {
        case _constants.FILE_UPLOAD_FAILURE:
          return 'D\'accord';
        case _constants.FILE_UPLOAD_SUCCESS:
          return 'Termin\xE9';
        case _constants.FILE_UPLOAD_ERROR:
          return 'Recommencer';
        default:
          return 'Importer';
      }
    }
  }, {
    key: 'continueButton',
    value: function continueButton() {
      return _react2.default.createElement(
        _Button2.default,
        {
          onClick: this.continueAction,
          variant: 'primary',
          disabled: this.disableContinueButton(),
          margin: _constants.XSMALL_SIDE_MARGIN,
          ref: this.setRef('confirmButton'),
          'data-automation': 'sdk-continue-import-button'
        },
        this.continueButtonMessage()
      );
    }
  }, {
    key: 'renderErroredContent',
    value: function renderErroredContent() {
      return _react2.default.createElement(
        _Alert2.default,
        {
          variant: 'error',
          ref: this.setRef('errorAlert'),
          liveRegion: _alertHelpers.liveRegion
        },
        'Erreur\xA0: un probl\xE8me est survenu lors du t\xE9l\xE9versement de votre fichier.'
      );
    }
  }, {
    key: 'renderSelectingContent',
    value: function renderSelectingContent(fileType) {
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          null,
          this.props.importMessage
        ),
        _react2.default.createElement(_ImportFileSelector2.default, {
          files: this.props.files,
          ref: this.setRef('fileSelector'),
          receiveFile: this.handleFile,
          acceptAttribute: fileType,
          'data-automation': 'sdk-import-file-selector'
        }),
        fileType === 'image/*' && _react2.default.createElement(
          'div',
          { className: styles.altTextWrapper },
          _react2.default.createElement(_TextInput2.default, {
            ref: this.setRef('altTextInput'),
            onChange: this.onAltTextChange,
            value: this.props.altText,
            label: _react2.default.createElement(
              'div',
              null,
              'Texte alternatif (facultatif)'
            ),
            type: 'text'
          })
        )
      );
    }
  }, {
    key: 'renderFailureContent',
    value: function renderFailureContent() {
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          _Alert2.default,
          {
            variant: 'error',
            ref: this.setRef('failureAlert'),
            'data-automation': 'sdk-import-error-alert',
            liveRegion: _alertHelpers.liveRegion
          },
          _react2.default.createElement(
            'div',
            null,
            'Erreur\xA0: un probl\xE8me est survenu lors de l\u2019importation de votre fichier.',
            _react2.default.createElement(
              _ToggleDetails2.default,
              {
                summary: _react2.default.createElement(
                  _Text2.default,
                  { size: 'small' },
                  'D\xE9tails de l\'erreur'
                )
              },
              _react2.default.createElement(
                _Text2.default,
                { size: 'small' },
                this.props.failureMessage
              )
            )
          )
        )
      );
    }
  }, {
    key: 'renderSuccessContent',
    value: function renderSuccessContent() {
      var file = this.props.files.get(0);
      var fileName = file ? file.name : '';
      return _react2.default.createElement(
        _Alert2.default,
        {
          variant: 'success',
          ref: this.setRef('successAlert'),
          'data-automation': 'sdk-import-success-alert',
          liveRegion: _alertHelpers.liveRegion
        },
        'Succ\xE8s\xA0: ' + fileName + ' import\xE9 avec succ\xE8s!'
      );
    }
  }, {
    key: 'renderImportingContent',
    value: function renderImportingContent() {
      return _react2.default.createElement(_Progress2.default, {
        label: 'Ach\xE8vement du processus d\'importation',
        valueNow: this.props.progressValue,
        ref: this.setRef('progressBar')
      });
    }
  }, {
    key: 'renderImportContent',
    value: function renderImportContent(fileType) {
      var uploadStatus = this.props.uploadStatus;

      switch (uploadStatus) {
        case _constants.FILE_UPLOAD_FAILURE:
          return this.renderFailureContent();
        case _constants.FILE_UPLOAD_SUCCESS:
          return this.renderSuccessContent();
        case _constants.FILE_UPLOAD_ERROR:
          return this.renderErroredContent();
        case _constants.FILE_UPLOAD_IMPORTING:
          return this.renderImportingContent();
        default:
          return this.renderSelectingContent(fileType);
      }
    }
  }, {
    key: 'renderContent',
    value: function renderContent() {
      var _this3 = this;

      if (typeof this.props.acceptFileType === 'string') {
        return this.renderImportContent(this.props.acceptFileType);
      }

      var selectedIndex = this.state.selectedTabIndex;
      return _react2.default.createElement(
        _TabList2.default,
        {
          selectedIndex: selectedIndex,
          onChange: this.handleTabChange
        },
        this.props.acceptFileType.map(function (_ref2, index) {
          var fileType = _ref2.fileType,
              title = _ref2.title;
          return _react2.default.createElement(
            _TabList.TabPanel,
            {
              key: title,
              title: title,
              disabled: _this3.props.files.size > 0 && index !== selectedIndex
            },
            _this3.renderImportContent(fileType)
          );
        })
      );
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        _Modal2.default,
        {
          open: this.props.modalOpen,
          size: 'small',
          onClose: this.props.onClose,
          onDismiss: this.cancelAction,
          label: 'Importer du contenu',
          ref: this.setRef('modal'),
          'data-automation': 'sdk-import-content-modal'
        },
        _react2.default.createElement(
          _Modal.ModalHeader,
          null,
          _react2.default.createElement(
            _Heading2.default,
            { level: 'reset', as: 'h2' },
            'Importer du contenu'
          ),
          _react2.default.createElement(_CloseButton2.default, {
            onClick: this.cancelAction,
            placement: 'end',
            offset: 'medium',
            variant: 'icon'
          })
        ),
        _react2.default.createElement(
          _Modal.ModalBody,
          null,
          this.renderContent()
        ),
        _react2.default.createElement(
          _Modal.ModalFooter,
          null,
          this.cancelButton(),
          this.continueButton()
        )
      );
    }
  }]);
  ImportModal.displayName = 'ImportModal'
  ;
  return ImportModal;
}(_react.Component), _class2.propTypes = {
  acceptFileType: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.arrayOf(_propTypes2.default.shape({
    fileType: _propTypes2.default.string,
    title: _propTypes2.default.string
  }))]).isRequired,
  altText: _propTypes2.default.string.isRequired, // passed in by connect
  clearAltText: _propTypes2.default.func.isRequired, // passed in by connect
  clearFiles: _propTypes2.default.func.isRequired, // passed in by connect
  closeModal: _propTypes2.default.func.isRequired, // passed in by connect
  closeOverride: _propTypes2.default.func,
  disableConfirm: _propTypes2.default.bool,
  failureMessage: _propTypes2.default.string.isRequired,
  files: _reactImmutableProptypes2.default.list.isRequired, // passed in by connect
  fileUpload: _propTypes2.default.func.isRequired,
  importMessage: _propTypes2.default.string.isRequired,
  modalOpen: _propTypes2.default.bool.isRequired, // passed in by connect
  onClose: _propTypes2.default.func,
  onContinue: _propTypes2.default.func.isRequired,
  progressValue: _propTypes2.default.number.isRequired,
  receiveFile: _propTypes2.default.func.isRequired, // passed in by connect
  setAltText: _propTypes2.default.func.isRequired, // passed in by connect
  setUploadStatus: _propTypes2.default.func.isRequired, // passed in by connect
  uploadStatus: _propTypes2.default.oneOf([_constants.FILE_UPLOAD_SELECT, _constants.FILE_UPLOAD_IMPORTING, _constants.FILE_UPLOAD_SUCCESS, _constants.FILE_UPLOAD_FAILURE, _constants.FILE_UPLOAD_ERROR]).isRequired // passed in by connect
}, _class2.defaultProps = {
  closeOverride: null,
  disableConfirm: false,
  onClose: function onClose() {}
}, _temp2)) || _class);
exports.default = ImportModal;