"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 _reactImmutableProptypes = _interopRequireDefault(require("react-immutable-proptypes"));

var _Alert = _interopRequireDefault(require("@instructure/ui-alerts/lib/components/Alert"));

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

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

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

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

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

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

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

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

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

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

var _Modal = _interopRequireWildcard(require("@instructure/quiz-common/lib/components/Modal"));

var _constants = require("@instructure/quiz-common/lib/constants");

var _theme = _interopRequireDefault(require("./theme"));

var _ImportFileSelector = _interopRequireDefault(require("./ImportFileSelector"));

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

var _dec, _class, _class2, _temp;

var styles = {
  componentId: 'ceoks',
  template: function template(theme) {
    return "\n\n.quiz-core__ImportModal--altTextWrapper {\n  margin-top: ".concat(theme.altTextMargin || 'inherit', ";\n}\n");
  },
  'altTextWrapper': 'quiz-core__ImportModal--altTextWrapper'
};
var ImportModal = (_dec = (0, _lib.default)(_theme.default, styles), _dec(_class = (_temp = _class2 =
/*#__PURE__*/
function (_Component) {
  (0, _inherits2.default)(ImportModal, _Component);

  function ImportModal() {
    var _getPrototypeOf2;

    var _this;

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

    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)(ImportModal)).call.apply(_getPrototypeOf2, [this].concat(args)));
    _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
      });
    };

    return _this;
  }

  (0, _createClass2.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 _react.default.createElement(_Button.default, {
        disabled: this.disableCancelButton(),
        onClick: this.cancelAction,
        margin: _constants.XSMALL_SIDE_MARGIN,
        ref: this.setRef('cancelImportButton'),
        "data-automation": "sdk-cancel-import-button"
      }, "Cancelar");
    }
  }, {
    key: "disableContinueButton",
    value: function disableContinueButton() {
      var _this$props2 = this.props,
          uploadStatus = _this$props2.uploadStatus,
          files = _this$props2.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 "Ok";

        case _constants.FILE_UPLOAD_SUCCESS:
          return "Feito";

        case _constants.FILE_UPLOAD_ERROR:
          return "Reiniciar";

        default:
          return "Importar";
      }
    }
  }, {
    key: "continueButton",
    value: function continueButton() {
      return _react.default.createElement(_Button.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 _react.default.createElement(_Alert.default, {
        variant: "error",
        ref: this.setRef('errorAlert'),
        liveRegion: _alertHelpers.liveRegion
      }, "Erro: houve um problema ao carregar seu arquivo.");
    }
  }, {
    key: "renderSelectingContent",
    value: function renderSelectingContent(fileType) {
      return _react.default.createElement("div", null, _react.default.createElement("div", null, this.props.importMessage), _react.default.createElement(_ImportFileSelector.default, {
        files: this.props.files,
        ref: this.setRef('fileSelector'),
        receiveFile: this.handleFile,
        acceptAttribute: fileType,
        "data-automation": "sdk-import-file-selector"
      }), fileType === 'image/*' && _react.default.createElement("div", {
        className: styles.altTextWrapper
      }, _react.default.createElement(_TextInput.default, {
        ref: this.setRef('altTextInput'),
        onChange: this.onAltTextChange,
        value: this.props.altText,
        label: _react.default.createElement("div", null, "texto alternativo (opcional)"),
        type: "text"
      })));
    }
  }, {
    key: "renderFailureContent",
    value: function renderFailureContent() {
      return _react.default.createElement("div", null, _react.default.createElement(_Alert.default, {
        variant: "error",
        ref: this.setRef('failureAlert'),
        "data-automation": "sdk-import-error-alert",
        liveRegion: _alertHelpers.liveRegion
      }, _react.default.createElement("div", null, "Erro: houve um problema ao importar seu arquivo.", _react.default.createElement(_ToggleDetails.default, {
        summary: _react.default.createElement(_Text.default, {
          size: "small"
        }, "Detalhes do erro")
      }, _react.default.createElement(_Text.default, {
        size: "small"
      }, this.props.failureMessage)))));
    }
  }, {
    key: "renderSuccessContent",
    value: function renderSuccessContent() {
      var file = this.props.files.get(0);
      var fileName = file ? file.name : '';
      return _react.default.createElement(_Alert.default, {
        variant: "success",
        ref: this.setRef('successAlert'),
        "data-automation": "sdk-import-success-alert",
        liveRegion: _alertHelpers.liveRegion
      }, "Sucesso: " + fileName + " foi importado com sucesso!");
    }
  }, {
    key: "renderImportingContent",
    value: function renderImportingContent() {
      return _react.default.createElement(_Progress.default, {
        label: "Conclus\xE3o do processo de importa\xE7\xE3o",
        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 _react.default.createElement(_TabList.default, {
        selectedIndex: selectedIndex,
        onChange: this.handleTabChange
      }, this.props.acceptFileType.map(function (_ref, index) {
        var fileType = _ref.fileType,
            title = _ref.title;
        return _react.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 _react.default.createElement(_Modal.default, {
        open: this.props.modalOpen,
        size: "small",
        onClose: this.props.onClose,
        onDismiss: this.cancelAction,
        label: "Importar conte\xFAdo",
        ref: this.setRef('modal'),
        "data-automation": "sdk-import-content-modal"
      }, _react.default.createElement(_Modal.ModalHeader, null, _react.default.createElement(_Heading.default, {
        level: "reset",
        as: "h2"
      }, "Importar conte\xFAdo"), _react.default.createElement(_CloseButton.default, {
        onClick: this.cancelAction,
        placement: "end",
        offset: "medium",
        variant: "icon"
      }, "Fechar")), _react.default.createElement(_Modal.ModalBody, null, this.renderContent()), _react.default.createElement(_Modal.ModalFooter, null, this.cancelButton(), this.continueButton()));
    }
  }]);
  ImportModal.displayName = "ImportModal";
  return ImportModal;
}(_react.Component), _class2.propTypes = {
  acceptFileType: _propTypes.default.oneOfType([_propTypes.default.string, _propTypes.default.arrayOf(_propTypes.default.shape({
    fileType: _propTypes.default.string,
    title: _propTypes.default.string
  }))]).isRequired,
  altText: _propTypes.default.string.isRequired,
  // passed in by connect
  clearAltText: _propTypes.default.func.isRequired,
  // passed in by connect
  clearFiles: _propTypes.default.func.isRequired,
  // passed in by connect
  closeModal: _propTypes.default.func.isRequired,
  // passed in by connect
  closeOverride: _propTypes.default.func,
  disableConfirm: _propTypes.default.bool,
  failureMessage: _propTypes.default.string.isRequired,
  files: _reactImmutableProptypes.default.list.isRequired,
  // passed in by connect
  fileUpload: _propTypes.default.func.isRequired,
  importMessage: _propTypes.default.string.isRequired,
  modalOpen: _propTypes.default.bool.isRequired,
  // passed in by connect
  onClose: _propTypes.default.func,
  onContinue: _propTypes.default.func.isRequired,
  progressValue: _propTypes.default.number.isRequired,
  receiveFile: _propTypes.default.func.isRequired,
  // passed in by connect
  setAltText: _propTypes.default.func.isRequired,
  // passed in by connect
  setUploadStatus: _propTypes.default.func.isRequired,
  // passed in by connect
  uploadStatus: _propTypes.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() {}
}, _temp)) || _class);
exports.default = ImportModal;