function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { log, func } from '../../util';
import { uid } from '../util';
var INPUT_STYLE = {
  position: 'absolute',
  top: 0,
  right: 0,
  fontSize: 9999,
  zIndex: 9999,
  opacity: 0,
  outline: 'none',
  cursor: 'pointer'
};

var IframeUploader =
/*#__PURE__*/
function (_React$Component) {
  _inherits(IframeUploader, _React$Component);

  function IframeUploader(_props) {
    var _this;

    _classCallCheck(this, IframeUploader);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(IframeUploader).call(this, _props));

    _defineProperty(_assertThisInitialized(_this), "state", {
      uploading: false
    });

    _defineProperty(_assertThisInitialized(_this), "file", {});

    _defineProperty(_assertThisInitialized(_this), "onLoad", function () {
      if (!_this.state.uploading) {
        return;
      }

      var _assertThisInitialize = _assertThisInitialized(_this),
          props = _assertThisInitialize.props,
          file = _assertThisInitialize.file;

      var response;

      try {
        var doc = _this.refs.iframe.contentDocument;
        var script = doc.getElementsByTagName('script')[0];

        if (script && script.parentNode === doc.body) {
          doc.body.removeChild(script);
        }

        response = doc.body.innerHTML;
        props.onSuccess(response, file);
      } catch (err) {
        log.warning('cross domain error for Upload. Maybe server should return document.domain script.');
        response = 'cross-domain';
        props.onError(err, null, file);
      }

      _this.endUpload();
    });

    _defineProperty(_assertThisInitialized(_this), "onSelect", function (e) {
      _this.file = {
        uid: uid(),
        name: e.target.value
      };

      _this.props.onSelect([_this.file]);
    });

    _this.domain = typeof document !== 'undefined' && document.domain ? document.domain : '';
    return _this;
  }

  _createClass(IframeUploader, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updateInputWH();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      this.updateInputWH();
    }
  }, {
    key: "startUpload",
    value: function startUpload() {
      this.upload(this.file);
      this.file = {};
    }
  }, {
    key: "upload",
    value: function upload(file) {
      var _this2 = this;

      if (!this.state.uploading) {
        // eslint-disable-next-line
        this.state.uploading = true;
        this.setState({
          uploading: true
        });
      }

      var beforeUpload = this.props.beforeUpload;

      if (!beforeUpload) {
        return this.post(file);
      }

      var before = beforeUpload(file);

      if (before && before.then) {
        before.then(function () {
          _this2.post(file);
        }, function () {
          _this2.endUpload();
        });
      } else if (before !== false) {
        this.post(file);
      } else {
        this.endUpload();
      }
    }
  }, {
    key: "endUpload",
    value: function endUpload() {
      this.file = {};

      if (this.state.uploading) {
        // eslint-disable-next-line
        this.state.uploading = false;
        this.setState({
          uploading: false
        });
      }
    }
  }, {
    key: "updateInputWH",
    value: function updateInputWH() {
      var rootNode = ReactDOM.findDOMNode(this);
      var inputNode = this.refs.input;
      inputNode.style.height = "".concat(rootNode.offsetHeight, "px");
      inputNode.style.width = "".concat(rootNode.offsetWidth, "px");
    }
  }, {
    key: "abort",
    value: function abort(file) {
      if (file) {
        var _uid = file;

        if (file && file.uid) {
          _uid = file.uid;
        }

        if (_uid === this.file.uid) {
          this.endUpload();
        }
      } else {
        this.endUpload();
      }
    }
  }, {
    key: "post",
    value: function post(file) {
      var formNode = this.refs.form;
      var dataSpan = this.refs.data;
      var data = this.props.data;

      if (typeof data === 'function') {
        data = data(file);
      }

      var inputs = document.createDocumentFragment();

      for (var key in data) {
        if (data.hasOwnProperty(key)) {
          var input = document.createElement('input');
          input.setAttribute('name', key);
          input.value = data[key];
          inputs.appendChild(input);
        }
      }

      dataSpan.appendChild(inputs);
      formNode.submit();
      dataSpan.innerHTML = '';
      this.props.onStart(file);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          disabled = _this$props.disabled,
          className = _this$props.className,
          children = _this$props.children,
          accept = _this$props.accept,
          name = _this$props.name,
          style = _this$props.style;
      var iframeName = "".concat(name, "-iframe");
      return React.createElement("span", {
        className: className,
        style: _objectSpread({
          position: 'relative',
          zIndex: 0,
          display: 'inline-block'
        }, style)
      }, !disabled ? React.createElement("iframe", {
        ref: "iframe",
        name: iframeName,
        onLoad: this.onLoad,
        style: {
          display: 'none'
        }
      }) : null, React.createElement("form", {
        ref: "form",
        method: "post",
        action: this.props.action,
        encType: "multipart/form-data",
        target: iframeName
      }, React.createElement("input", {
        ref: "input",
        type: "file",
        accept: accept,
        name: name,
        onChange: this.onSelect,
        style: INPUT_STYLE
      }), React.createElement("input", {
        name: "_documentDomain",
        value: this.domain,
        type: "hidden"
      }), React.createElement("span", {
        ref: "data"
      })), children);
    }
  }]);

  return IframeUploader;
}(React.Component);

_defineProperty(IframeUploader, "propTypes", {
  style: PropTypes.object,
  action: PropTypes.string.isRequired,
  name: PropTypes.string.isRequired,
  data: PropTypes.oneOfType([PropTypes.object, PropTypes.func]),
  disabled: PropTypes.bool,
  className: PropTypes.string,
  children: PropTypes.node,
  headers: PropTypes.object,
  autoUpload: PropTypes.bool,
  onSelect: PropTypes.func,
  beforeUpload: PropTypes.func,
  onStart: PropTypes.func,
  onSuccess: PropTypes.func,
  onError: PropTypes.func,
  accept: PropTypes.string
});

_defineProperty(IframeUploader, "defaultProps", {
  name: 'file',
  onSelect: func.noop,
  beforeUpload: func.noop,
  onStart: func.noop,
  onSuccess: func.noop,
  onError: func.noop,
  onAbort: func.noop
});

export default IframeUploader;