function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) { ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } } return n; }, _extends.apply(null, arguments); }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) { o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) { if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } } return t; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) { n[e] = r[e]; } return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0) { ; } } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _createSuper(t) { var r = _isNativeReflectConstruct(); return function () { var e, o = _getPrototypeOf(t); if (r) { var s = _getPrototypeOf(this).constructor; e = Reflect.construct(o, arguments, s); } else e = o.apply(this, arguments); return _possibleConstructorReturn(this, e); }; }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * The OpenSearch Contributors require contributions made to
 * this file be licensed under the Apache-2.0 license or a
 * compatible open source license.
 *
 * Modifications Copyright OpenSearch Contributors. See
 * GitHub history for details.
 */

/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { Component } from 'react';
import PropTypes from "prop-types";
import classNames from 'classnames';
import { keysOf } from '../../common';
import { OuiValidatableControl } from '../validatable_control';
import { OuiButtonEmpty } from '../../button';
import { OuiProgress } from '../../progress';
import { OuiIcon } from '../../icon';
import { OuiI18n } from '../../i18n';
import { OuiLoadingSpinner } from '../../loading';
import { htmlIdGenerator } from '../../../services/accessibility';
var displayToClassNameMap = {
  default: null,
  large: 'ouiFilePicker--large'
};
export var DISPLAYS = keysOf(displayToClassNameMap);
export var OuiFilePicker = /*#__PURE__*/function (_Component) {
  _inherits(OuiFilePicker, _Component);
  var _super = _createSuper(OuiFilePicker);
  function OuiFilePicker() {
    var _this;
    _classCallCheck(this, OuiFilePicker);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _super.call.apply(_super, [this].concat(args));
    _defineProperty(_assertThisInitialized(_this), "state", {
      promptText: null,
      isHoveringDrop: false
    });
    _defineProperty(_assertThisInitialized(_this), "fileInput", null);
    _defineProperty(_assertThisInitialized(_this), "handleChange", function (filesSelected) {
      if (!_this.fileInput) return;
      if (_this.fileInput.files && _this.fileInput.files.length > 1) {
        _this.setState({
          promptText: "".concat(_this.fileInput.files.length, " ").concat(filesSelected)
        });
      } else if (_this.fileInput.files && _this.fileInput.files.length === 0) {
        _this.setState({
          promptText: null
        });
      } else {
        _this.setState({
          promptText: _this.fileInput.value.split('\\').pop()
        });
      }
      var onChange = _this.props.onChange;
      if (onChange) {
        onChange(_this.fileInput.files);
      }
    });
    _defineProperty(_assertThisInitialized(_this), "removeFiles", function (e) {
      e.stopPropagation();
      e.preventDefault();
      if (!_this.fileInput) return;
      _this.fileInput.value = '';
      _this.handleChange(null);
    });
    _defineProperty(_assertThisInitialized(_this), "showDrop", function () {
      if (!_this.props.disabled) {
        _this.setState({
          isHoveringDrop: true
        });
      }
    });
    _defineProperty(_assertThisInitialized(_this), "hideDrop", function () {
      _this.setState({
        isHoveringDrop: false
      });
    });
    return _this;
  }
  _createClass(OuiFilePicker, [{
    key: "render",
    value: function render() {
      var _this2 = this;
      return /*#__PURE__*/React.createElement(OuiI18n, {
        tokens: ['ouiFilePicker.clearSelectedFiles', 'ouiFilePicker.filesSelected'],
        defaults: ['Clear selected files', 'files selected']
      }, function (_ref) {
        var _ref2 = _slicedToArray(_ref, 2),
          clearSelectedFiles = _ref2[0],
          filesSelected = _ref2[1];
        var _this2$props = _this2.props,
          id = _this2$props.id,
          name = _this2$props.name,
          initialPromptText = _this2$props.initialPromptText,
          className = _this2$props.className,
          disabled = _this2$props.disabled,
          compressed = _this2$props.compressed,
          onChange = _this2$props.onChange,
          isInvalid = _this2$props.isInvalid,
          fullWidth = _this2$props.fullWidth,
          isLoading = _this2$props.isLoading,
          display = _this2$props.display,
          rest = _objectWithoutProperties(_this2$props, ["id", "name", "initialPromptText", "className", "disabled", "compressed", "onChange", "isInvalid", "fullWidth", "isLoading", "display"]);
        var promptId = htmlIdGenerator()();
        if (id) {
          promptId = "".concat(id, "-filePicker__prompt");
        }
        var isOverridingInitialPrompt = _this2.state.promptText != null;
        var normalFormControl = display === 'default';
        var classes = classNames('ouiFilePicker', displayToClassNameMap[display], {
          ouiFilePicker__showDrop: _this2.state.isHoveringDrop,
          'ouiFilePicker--compressed': compressed,
          'ouiFilePicker--fullWidth': fullWidth,
          'ouiFilePicker-isInvalid': isInvalid,
          'ouiFilePicker-isLoading': isLoading,
          'ouiFilePicker-hasFiles': isOverridingInitialPrompt
        }, className);
        var clearButton;
        if (isLoading && normalFormControl) {
          // Override clear button with loading spinner if it is in loading state
          clearButton = /*#__PURE__*/React.createElement(OuiLoadingSpinner, {
            className: "ouiFilePicker__loadingSpinner"
          });
        } else if (isOverridingInitialPrompt) {
          if (normalFormControl) {
            clearButton = /*#__PURE__*/React.createElement("button", {
              type: "button",
              "aria-label": clearSelectedFiles,
              className: "ouiFilePicker__clearButton",
              onClick: _this2.removeFiles
            }, /*#__PURE__*/React.createElement(OuiIcon, {
              className: "ouiFilePicker__clearIcon",
              type: "cross"
            }));
          } else {
            clearButton = /*#__PURE__*/React.createElement(OuiButtonEmpty, {
              "aria-label": clearSelectedFiles,
              className: "ouiFilePicker__clearButton",
              size: "xs",
              onClick: _this2.removeFiles
            }, /*#__PURE__*/React.createElement(OuiI18n, {
              token: "ouiFilePicker.removeSelected",
              default: "Remove"
            }));
          }
        } else {
          clearButton = null;
        }
        var loader = !normalFormControl && isLoading && /*#__PURE__*/React.createElement(OuiProgress, {
          size: "xs",
          color: "accent",
          position: "absolute"
        });
        return /*#__PURE__*/React.createElement("div", {
          className: classes
        }, /*#__PURE__*/React.createElement("div", {
          className: "ouiFilePicker__wrap"
        }, /*#__PURE__*/React.createElement(OuiValidatableControl, {
          isInvalid: isInvalid
        }, /*#__PURE__*/React.createElement("input", _extends({
          type: "file",
          id: id,
          name: name,
          className: "ouiFilePicker__input",
          onChange: function onChange() {
            return _this2.handleChange(filesSelected);
          },
          ref: function ref(input) {
            _this2.fileInput = input;
          },
          onDragOver: _this2.showDrop,
          onDragLeave: _this2.hideDrop,
          onDrop: _this2.hideDrop,
          disabled: disabled,
          "aria-describedby": promptId
        }, rest))), /*#__PURE__*/React.createElement("div", {
          className: "ouiFilePicker__prompt",
          id: promptId
        }, /*#__PURE__*/React.createElement(OuiIcon, {
          className: "ouiFilePicker__icon",
          type: "importAction",
          size: normalFormControl ? 'm' : 'l',
          "aria-hidden": "true"
        }), /*#__PURE__*/React.createElement("div", {
          className: "ouiFilePicker__promptText"
        }, _this2.state.promptText || initialPromptText), clearButton, loader)));
      });
    }
  }]);
  return OuiFilePicker;
}(Component);

// @internal
_defineProperty(OuiFilePicker, "defaultProps", {
  initialPromptText: 'Select or drag and drop a file',
  compressed: false,
  display: 'large'
});
OuiFilePicker.propTypes = {
  id: PropTypes.string,
  name: PropTypes.string,
  className: PropTypes.string,
  /**
     * The content that appears in the dropzone if no file is attached
     */
  initialPromptText: PropTypes.node,
  /**
     * Use as a callback to access the HTML FileList API
     */
  onChange: PropTypes.func,
  /**
     * Reduces the size to a typical (compressed) input
     */
  compressed: PropTypes.bool,
  /**
     * Size or type of display;
     * `default` for normal height, similar to other controls;
     * `large` for taller size
     */
  display: PropTypes.oneOf(["default", "large"]),
  fullWidth: PropTypes.bool,
  isInvalid: PropTypes.bool,
  isLoading: PropTypes.bool,
  disabled: PropTypes.bool,
  "aria-label": PropTypes.string,
  "data-test-subj": PropTypes.string
};
// @internal
export var OuiCompressedFilePicker = /*#__PURE__*/function (_OuiFilePicker) {
  _inherits(OuiCompressedFilePicker, _OuiFilePicker);
  var _super2 = _createSuper(OuiCompressedFilePicker);
  function OuiCompressedFilePicker() {
    _classCallCheck(this, OuiCompressedFilePicker);
    return _super2.apply(this, arguments);
  }
  return OuiCompressedFilePicker;
}(OuiFilePicker);

/* OUI -> EUI Aliases: Build-Time */
_defineProperty(OuiCompressedFilePicker, "defaultProps", _objectSpread(_objectSpread({}, OuiFilePicker.defaultProps), {}, {
  compressed: true
}));
/* OUI -> EUI Aliases: Build-Time */export { EuiFilePicker, EuiCompressedFilePicker } from '../../../eui_components/form/file_picker/file_picker';