'use strict';

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

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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDropzone = require('react-dropzone');

var _reactDropzone2 = _interopRequireDefault(_reactDropzone);

var _Icon = require('../Icon');

var _Icon2 = _interopRequireDefault(_Icon);

var _bind = require('classnames/bind');

var _bind2 = _interopRequireDefault(_bind);

var _style = require('./style.scss');

var _style2 = _interopRequireDefault(_style);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: 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) : subClass.__proto__ = superClass; }

/**
 * The FileUpload component.
 */

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

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

    var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(FileUpload).call(this, props));

    _this.state = {
      value: _this.props.value,
      files: []
    };

    _this._normalizeValue = function (value) {
      if (!value || value === '') {
        return [];
      } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
        return value;
      } else {
        var file = value.match(/.*\/(.*)$/);
        return [{ preview: value, name: file && file[1] ? file[1] : null }];
      }
    };

    _this.componentWillMount = function () {
      if (_this.props.value && _this.props.value !== '' && _this.props.showPreview) {
        _this.setState({ files: _this._normalizeValue(_this.props.value) });
      }
    };

    _this.componentWillReceiveProps = function (nextProps) {
      if (nextProps.value !== _this.props.value) {
        _this.setState({ files: _this._normalizeValue(nextProps.value) });
      }
    };

    _this.handleChange = function () {
      if (typeof _this.props.changeCallback === 'function') {
        _this.props.changeCallback({
          target: {
            name: _this.props.name,
            value: _this.state.files
          }
        });
      }
    };

    _this.handleUpload = function (files) {
      if (!_this.props.disabled) {
        _this.setState({ files: files }, function () {
          this.handleChange();
        });
      }
    };

    _this.handleRemove = function (index) {
      var savedFiles = _this.state.files;
      savedFiles.splice(index, 1);
      _this.setState({ files: savedFiles }, function () {
        this.handleChange();
      });
    };

    _this.getPreview = function () {
      var imgStyle = {
        maxWidth: _this.props.previewSize + 'px',
        maxHeight: _this.props.previewSize + 'px'
      };
      return _this.state.files.map(function (file, index) {
        return _react2.default.createElement(
          'div',
          { key: index, className: _style2.default.image },
          _react2.default.createElement('img', { style: imgStyle, src: file.preview }),
          _react2.default.createElement(_Icon2.default, { name: 'icon-delete-1', height: '16', width: '16', fill: '#233040', onClick: _this.handleRemove.bind(_this, index) })
        );
      });
    };

    return _this;
  }

  _createClass(FileUpload, [{
    key: 'render',
    value: function render() {
      var _props = this.props;
      var label = _props.label;
      var value = _props.value;
      var optClass = _props.optClass;
      var showPreview = _props.showPreview;
      var previewSize = _props.previewSize;
      var changeCallback = _props.changeCallback;

      var other = _objectWithoutProperties(_props, ['label', 'value', 'optClass', 'showPreview', 'previewSize', 'changeCallback']);

      var cx = _bind2.default.bind(_style2.default);
      var disabledClass = this.props.disabled ? _style2.default['disabled'] : '';
      var fileUploadClass = cx(_style2.default['file-upload-component'], optClass, disabledClass);

      return _react2.default.createElement(
        'div',
        { className: fileUploadClass },
        label ? _react2.default.createElement(
          'label',
          null,
          label
        ) : null,
        _react2.default.createElement(
          _reactDropzone2.default,
          _extends({ onDrop: this.handleUpload, className: _style2.default.dropzone, activeClassName: _style2.default.active, disableClick: this.props.disabled, multiple: false }, other),
          _react2.default.createElement(
            'div',
            null,
            'Drag and drop here to upload files or click to browse'
          )
        ),
        this.state.files[0] ? _react2.default.createElement(
          'div',
          { className: _style2.default.filename },
          _react2.default.createElement(
            'span',
            null,
            'Filename:'
          ),
          ' ',
          this.state.files[0].name
        ) : null,
        showPreview ? _react2.default.createElement(
          'div',
          { className: _style2.default.preview },
          this.getPreview()
        ) : null
      );
    }
  }]);

  return FileUpload;
}(_react2.default.Component);

FileUpload.defaultProps = {
  disabled: false,
  value: '',
  showPreview: false,
  previewSize: 200
};
FileUpload.propTypes = {
  /**
   * Whether the FileUpload is disabled.
   */
  disabled: _react2.default.PropTypes.bool,
  /**
   * Text shown above the FileUpload.
   */
  label: _react2.default.PropTypes.string,
  /**
   * Value of the FileUpload (can be path string or an array of file objects).
   */
  value: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.array, _react2.default.PropTypes.string]),
  /**
   * Name of the FileUpload.
   */
  name: _react2.default.PropTypes.string,
  /**
   * Whether to show the preview under the FileUpload.
   */
  showPreview: _react2.default.PropTypes.bool,
  /**
   * The preview size (maximum width and height).
   */
  previewSize: _react2.default.PropTypes.number,
  /**
   * Optional styles to add to the FileUpload.
   */
  optClass: _react2.default.PropTypes.string,
  /**
   * A callback function to be called when the FileUpload changes.
   */
  changeCallback: _react2.default.PropTypes.func
};
exports.default = FileUpload;