'use strict';

exports.__esModule = true;

var _isEqual2 = require('lodash/isEqual');

var _isEqual3 = _interopRequireDefault(_isEqual2);

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var React = _interopRequireWildcard(_react);

var _rsuiteIntl = require('rsuite-intl');

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _utils = require('./utils');

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

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

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

function _defaults(obj, defaults) { var keys = Object.getOwnPropertyNames(defaults); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = Object.getOwnPropertyDescriptor(defaults, key); if (value && value.configurable && obj[key] === undefined) { Object.defineProperty(obj, key, value); } } return obj; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : _defaults(subClass, superClass); }

var getSize = function getSize() {
  var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

  var K = 1024;
  var M = 1024 * 1024;
  var G = 1024 * 1024 * 1024;

  if (size > G) {
    return (size / M).toFixed(2) + 'GB';
  }

  if (size > M) {
    return (size / M).toFixed(2) + 'MB';
  }

  if (size > K) {
    return (size / K).toFixed(2) + 'KB';
  }
  return size + 'B';
};

var UploadFileItem = function (_React$Component) {
  _inherits(UploadFileItem, _React$Component);

  function UploadFileItem(props) {
    _classCallCheck(this, UploadFileItem);

    var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));

    _this.handleRemove = function (event) {
      var _this$props = _this.props,
          disabled = _this$props.disabled,
          onCancel = _this$props.onCancel,
          file = _this$props.file;


      if (disabled) {
        return;
      }

      onCancel && onCancel(file.fileKey, event);
    };

    _this.handlePreview = function (event) {
      var _this$props2 = _this.props,
          disabled = _this$props2.disabled,
          onPreview = _this$props2.onPreview,
          file = _this$props2.file;

      if (disabled) {
        return;
      }
      onPreview && onPreview(file, event);
    };

    _this.handleReupload = function (event) {
      var _this$props3 = _this.props,
          disabled = _this$props3.disabled,
          onReupload = _this$props3.onReupload,
          file = _this$props3.file;

      if (disabled) {
        return;
      }
      onReupload && onReupload(file, event);
    };

    _this.addPrefix = function (name) {
      return (0, _utils.prefix)(_this.props.classPrefix)(name);
    };

    _this.state = {
      thumbnail: null
    };
    return _this;
  }

  UploadFileItem.prototype.componentWillMount = function componentWillMount() {
    this.getThumbnail();
  };

  UploadFileItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
    if ((0, _isEqual3.default)(nextProps, this.props)) {
      this.getThumbnail(nextProps);
    }
  };

  UploadFileItem.prototype.getThumbnail = function getThumbnail(nextProps) {
    var _this2 = this;

    var _ref = nextProps || this.props,
        file = _ref.file;

    if (file.blobFile) {
      (0, _utils.previewFile)(file.blobFile, function (previewImage) {
        _this2.setState({ previewImage: previewImage });
      });
    }
  };

  UploadFileItem.prototype.renderProgressBar = function renderProgressBar() {
    var _props = this.props,
        disabled = _props.disabled,
        file = _props.file;
    var _file$progress = file.progress,
        progress = _file$progress === undefined ? 0 : _file$progress,
        status = file.status;

    var show = !disabled && status === 'uploading';
    var visibility = show ? 'visible' : 'hidden';
    var wrapStyle = {
      visibility: visibility
    };
    var progressbarStyle = {
      width: progress + '%'
    };
    return React.createElement(
      'div',
      { className: this.addPrefix('progress'), style: wrapStyle },
      React.createElement('div', { className: this.addPrefix('progress-bar'), style: progressbarStyle })
    );
  };

  UploadFileItem.prototype.renderPreview = function renderPreview() {
    var previewImage = this.state.previewImage;
    var file = this.props.file;


    if (previewImage && file.blobFile) {
      return React.createElement(
        'div',
        { className: this.addPrefix('preview') },
        React.createElement('img', {
          role: 'presentation',
          src: previewImage,
          alt: file.blobFile.name,
          onClick: this.handlePreview
        })
      );
    }
    return null;
  };

  UploadFileItem.prototype.renderLoading = function renderLoading() {
    var _classNames;

    var file = this.props.file;

    var uploading = file.status === 'uploading';
    var classes = (0, _classnames2.default)(this.addPrefix('icon-wrapper'), (_classNames = {}, _classNames[this.addPrefix('icon-loading')] = uploading, _classNames));
    return React.createElement(
      'div',
      { className: classes },
      React.createElement('i', { className: this.addPrefix('icon') })
    );
  };

  UploadFileItem.prototype.renderRemoveButton = function renderRemoveButton() {
    return React.createElement(
      'a',
      {
        'aria-label': 'Remove',
        className: this.addPrefix('btn-remove'),
        onClick: this.handleRemove,
        role: 'button',
        tabIndex: '-1'
      },
      React.createElement(
        'span',
        { 'aria-hidden': 'true' },
        '\xD7'
      )
    );
  };

  UploadFileItem.prototype.renderErrorStatus = function renderErrorStatus() {
    var file = this.props.file;

    if (file.status === 'error') {
      return React.createElement(
        'div',
        { className: this.addPrefix('status') },
        React.createElement(_rsuiteIntl.FormattedMessage, { id: 'error' }),
        React.createElement(
          'a',
          { role: 'button', tabIndex: '-1', onClick: this.handleReupload },
          React.createElement('i', { className: this.addPrefix('icon-reupload') })
        )
      );
    }
    return null;
  };

  UploadFileItem.prototype.renderFileSize = function renderFileSize() {
    var file = this.props.file;

    if (file.status !== 'error' && file.blobFile && file.blobFile.size) {
      return React.createElement(
        'span',
        { className: this.addPrefix('size') },
        getSize(file.blobFile.size)
      );
    }
    return null;
  };

  UploadFileItem.prototype.renderFilePanel = function renderFilePanel() {
    var file = this.props.file;

    return React.createElement(
      'div',
      { className: this.addPrefix('panel') },
      React.createElement(
        'div',
        { className: this.addPrefix('content') },
        React.createElement(
          'a',
          { role: 'presentation', className: this.addPrefix('title'), onClick: this.handlePreview },
          file.name
        ),
        this.renderErrorStatus(),
        this.renderFileSize()
      )
    );
  };

  UploadFileItem.prototype.render = function render() {
    var _classNames2;

    var _props2 = this.props,
        disabled = _props2.disabled,
        file = _props2.file,
        classPrefix = _props2.classPrefix,
        listType = _props2.listType,
        className = _props2.className,
        rest = _objectWithoutProperties(_props2, ['disabled', 'file', 'classPrefix', 'listType', 'className']);

    var classes = (0, _classnames2.default)(classPrefix, className, this.addPrefix(listType), (_classNames2 = {}, _classNames2[this.addPrefix('has-error')] = file.status === 'error', _classNames2[this.addPrefix('disabled')] = disabled, _classNames2));
    var unhandled = (0, _utils.getUnhandledProps)(UploadFileItem, rest);

    if (listType === 'picture') {
      return React.createElement(
        'div',
        { className: classes },
        this.renderLoading(),
        this.renderPreview(),
        this.renderErrorStatus(),
        this.renderRemoveButton()
      );
    }

    if (listType === 'picture-text') {
      return React.createElement(
        'div',
        { className: classes },
        this.renderLoading(),
        this.renderPreview(),
        this.renderFilePanel(),
        this.renderProgressBar(),
        this.renderRemoveButton()
      );
    }

    return React.createElement(
      'div',
      _extends({}, unhandled, { className: classes }),
      this.renderLoading(),
      this.renderFilePanel(),
      this.renderProgressBar(),
      this.renderRemoveButton()
    );
  };

  return UploadFileItem;
}(React.Component);

UploadFileItem.defaultProps = {
  listType: 'text'
};
UploadFileItem.handledProps = ['className', 'classPrefix', 'disabled', 'file', 'listType', 'onCancel', 'onPreview', 'onReupload'];
UploadFileItem.propTypes = {
  file: _propTypes2.default.shape({
    fileKey: _propTypes2.default.oneOfType([_propTypes2.default.number, _propTypes2.default.string]).isRequired,
    name: _propTypes2.default.string.isRequired,

    // https://developer.mozilla.org/zh-CN/docs/Web/API/File
    blobFile: function blobFile() {
      return (typeof File === 'function' ? _propTypes2.default.instanceOf(File) : _propTypes2.default.any).apply(this, arguments);
    },
    status: _propTypes2.default.oneOf(['inited', 'uploading', 'error', 'finished']),
    progress: _propTypes2.default.number
  }).isRequired,
  listType: _propTypes2.default.oneOf(['text', 'picture-text', 'picture']).isRequired,
  disabled: _propTypes2.default.bool,
  onCancel: _propTypes2.default.func,
  onPreview: _propTypes2.default.func,
  onReupload: _propTypes2.default.func,
  className: _propTypes2.default.string,
  classPrefix: _propTypes2.default.string
};
exports.default = (0, _utils.defaultProps)({
  classPrefix: 'uploader-file-item'
})(UploadFileItem);