"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _formiga = require("formiga");
var _FInputAddon = require("../../addon/FInputAddon.cjs");
var _inputPropTypes = require("../../props/inputPropTypes.cjs");
var _inputDefaultProps = require("../../props/inputDefaultProps.cjs");
var _ProgressBar = _interopRequireDefault(require("./ProgressBar"));
var _withWrapControlled = _interopRequireDefault(require("../../helpers/props/withWrapControlled.cjs"));
var _useFileTypeIcon = _interopRequireDefault(require("./useFileTypeIcon.cjs"));
var _FFHidden = _interopRequireDefault(require("./FFHidden.cjs"));
var _FFInput = _interopRequireDefault(require("./FFInput.cjs"));
var _FFClear = _interopRequireDefault(require("./FFClear.cjs"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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; }; return _extends.apply(this, arguments); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _FInputFile = props => {
  var {
    icon,
    onDownload,
    iconMap,
    value,
    setValue
  } = props;
  var input = (0, _formiga.useInput)(_objectSpread({}, props));
  var [hasValue, setHasValue] = (0, _react.useState)((value === null || value === void 0 ? void 0 : value.buffer) || (value === null || value === void 0 ? void 0 : value.size) > 0);
  var [progress, setProgress] = (0, _react.useState)(undefined);
  var [status, setStatus] = (0, _react.useState)(undefined);
  var [statusMsg, setStatusMsg] = (0, _react.useState)(undefined);
  var ftypeIcon = (0, _useFileTypeIcon.default)(value === null || value === void 0 ? void 0 : value.type, icon, iconMap);
  (0, _react.useEffect)(() => {
    if (value) {
      if (value.buffer == undefined || value.buffer.length == 0) {
        if (value.size > 0) {
          input.setValidity('');
        }
      }
    }
  }, [value, input]);
  var handleChange = (0, _react.useCallback)(event => {
    event.persist();
    try {
      var reader = new FileReader();
      reader.onerror = e => {
        var st_msg = '';
        switch (e.target.error.code) {
          case e.target.error.NOT_FOUND_ERR:
            st_msg = 'File not found!';
            break;
          case e.target.error.NOT_READABLE_ERR:
            st_msg = 'Unreadable file';
            break;
          case e.target.error.ABORT_ERR:
            break;
          // noop
          default:
            st_msg = 'Error reading file';
        }
        setStatusMsg(st_msg);
        setStatus('error');
        setValue({}, true, event);
        setHasValue(false);
      };
      reader.onabort = _e => {
        setStatus('abort');
        setStatusMsg('Aborted');
        setProgress(undefined);
        setValue({}, true, event);
        setHasValue(false);
      };
      reader.onprogress = e => {
        // e is an ProgressEvent.
        if (e.lengthComputable) {
          setProgress(Math.round(e.loaded / e.total * 100));
        }
      };
      reader.onloadstart = _e => {
        setProgress(0);
        setStatus('uploading');
        setStatusMsg('Loading file');
      };
      reader.onload = e => {
        var file = event.target.files[0];
        setProgress(100);
        setStatusMsg('File loaded');
        var nValue = {
          name: file.name,
          size: file.size,
          type: file.type,
          buffer: new Uint8Array(e.target.result)
        };
        setValue(nValue, true, e);
        setHasValue(true);

        //input.setValue(file)
        input.validate();
      };
      reader.readAsArrayBuffer(event.target.files[0]);
    } catch (e) {
      console.error(e);
      setStatus(undefined);
      setStatusMsg(undefined);
      setHasValue(false);
    }
  }, [setValue, input]);
  var handleClear = (0, _react.useCallback)(event => {
    setProgress(0);
    setStatus(undefined);
    setStatusMsg(undefined);
    setValue({}, true, event);
    setHasValue(false);
    input.validate();
  }, [setValue, input]);
  var handleBrowse = (0, _react.useCallback)(() => {
    //let evt = document.createEvent("MouseEvents")
    //evt.initEvent("click", true, false)     
    //input.node.dispatchEvent(evt)
    //input.dispatchEvent('click', {cancelable: false})
    input.node.click();
  }, [input]);
  var handleDownload = (0, _react.useCallback)(ev => {
    if (onDownload != undefined) {
      onDownload(value, ev);
    }
  }, [value, onDownload]);

  // console.log(`status ${status} - vname ${value?.name} - files ${input?.node?.files.length} · ${ input?.node?.files[0]?.name}`)

  return /*#__PURE__*/_react.default.createElement(_FInputAddon.FInputAddon, _extends({}, props, {
    valid: input.valid,
    invalid: !input.valid,
    feedback: input.feedback,
    icon: ftypeIcon,
    middleElement: status != undefined ? /*#__PURE__*/_react.default.createElement(_ProgressBar.default, {
      progress: progress,
      ftypeIcon: ftypeIcon,
      bsSize: props.bsSize
    }) : null
  }), /*#__PURE__*/_react.default.createElement(_FFHidden.default, _extends({}, props, {
    onChange: handleChange,
    hasValue: hasValue,
    inputRef: input.ref
  })), /*#__PURE__*/_react.default.createElement(_FFInput.default, _extends({}, props, {
    statusMsg: statusMsg,
    hasValue: hasValue,
    value: value,
    valid: input.valid,
    onDownload: handleDownload,
    onBrowse: handleBrowse,
    ftypeIcon: ftypeIcon
  })), /*#__PURE__*/_react.default.createElement(_FFClear.default, {
    hasValue: hasValue,
    onClear: handleClear
  }));
};
var FInputFile = (0, _withWrapControlled.default)(_FInputFile);
FInputFile.propTypes = _objectSpread(_objectSpread({}, _inputPropTypes.inputPropTypes), {}, {
  onDownload: _propTypes.default.func,
  accept: _propTypes.default.string,
  iconMap: _propTypes.default.object
});
FInputFile.defaultProps = _objectSpread(_objectSpread({}, _inputDefaultProps.inputDefaultProps), {}, {
  icon: 'file',
  value: undefined
});
var _default = FInputFile;
exports.default = _default;