import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.array.join.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.function.name.js';
import 'core-js/modules/es.regexp.exec.js';
import 'core-js/modules/es.string.includes.js';
import 'core-js/modules/es.string.match.js';
import React__default, { useState, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { InlineNotification, TextInput, FileUploaderDropContainer } from '@carbon/react';
import classnames from 'classnames';
import { settings } from '../../constants/Settings.js';
import Button from '../Button/Button.js';
import { fetchDataURL } from '../../utils/cardUtilityFunctions.js';
import { Image } from '@carbon/icons-react';

var _excluded = ["hasInsertFromUrl", "onBrowseClick", "i18n", "onUpload", "accept", "validateUploadedImage", "maxFileSizeInBytes", "testId"];
var iotPrefix = settings.iotPrefix;
var i18nDefaults = {
  dropContainerLabelText: 'Drag file here or click to upload file',
  dropContainerDescText: 'Max file size is 1MB. Supported file types are: APNG, AVIF, GIF, JPEG, PNG, WebP',
  uploadByURLCancel: 'Cancel',
  uploadByURLButton: 'OK',
  browseImages: 'Add from gallery',
  insertUrl: 'Insert from URL',
  urlInput: 'Type or insert URL',
  errorTitle: 'Upload error: ',
  fileTooLarge: 'Image file is too large',
  wrongFileType: function wrongFileType(accept) {
    return "This file is not one of the accepted file types, ".concat(accept.join(', '));
  }
};
var propTypes = {
  accept: PropTypes.arrayOf(PropTypes.string),
  onBrowseClick: PropTypes.func,
  onUpload: PropTypes.func,
  /** the maximum file size in bytes */
  maxFileSizeInBytes: PropTypes.number,
  hasInsertFromUrl: PropTypes.bool,
  /** a callback invoked with the image information, if you want to fail validation return a string with the error */
  validateUploadedImage: PropTypes.func,
  i18n: PropTypes.shape({
    dropContainerLabelText: PropTypes.string,
    dropContainerDescText: PropTypes.string,
    uploadByURLCancel: PropTypes.string,
    uploadByURLButton: PropTypes.string,
    browseImages: PropTypes.string,
    insertUrl: PropTypes.string,
    urlInput: PropTypes.string,
    fileTooLarge: PropTypes.string,
    wrongFileType: PropTypes.func,
    errorTitle: PropTypes.string
  }),
  testId: PropTypes.string
};
var defaultProps = {
  accept: ['APNG', 'AVIF', 'GIF', 'JPEG', 'JPG', 'PNG', 'WebP'],
  maxFileSizeInBytes: 1048576,
  validateUploadedImage: null,
  onBrowseClick: function onBrowseClick() {},
  onUpload: function onUpload() {},
  hasInsertFromUrl: false,
  i18n: i18nDefaults,
  testId: 'image-uploader'
};
var ImageUploader = function ImageUploader(_ref) {
  var hasInsertFromUrl = _ref.hasInsertFromUrl,
    onBrowseClick = _ref.onBrowseClick,
    i18n = _ref.i18n,
    onUpload = _ref.onUpload,
    accept = _ref.accept,
    validateUploadedImage = _ref.validateUploadedImage,
    maxFileSizeInBytes = _ref.maxFileSizeInBytes,
    testId = _ref.testId,
    other = _objectWithoutProperties(_ref, _excluded);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    fromURL = _useState2[0],
    setFromURL = _useState2[1];
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    error = _useState4[0],
    setError = _useState4[1];
  var _useState5 = useState('default'),
    _useState6 = _slicedToArray(_useState5, 2),
    buttonSize = _useState6[0],
    setButtonSize = _useState6[1];
  var imgRef = useRef(null);
  useEffect(function () {
    if (other.width < 520) {
      setButtonSize('small');
    } else {
      setButtonSize('default');
    }
  }, [other.width]);
  var handleFromURLClick = function handleFromURLClick() {
    setFromURL(true);
  };
  var handleCancelFromURLClick = function handleCancelFromURLClick() {
    setFromURL(false);
  };
  var handleUploadByURL = function handleUploadByURL() {
    var url = imgRef.current.value;
    if (url === '') {
      return;
    }
    fetchDataURL(url, setError).then(function (imageData) {
      if (imageData !== undefined) {
        onUpload(imageData);
      }
    }).catch(function (e) {
      return setError("".concat(e.message));
    });
  };
  var handleOnChange = function handleOnChange(_event, files) {
    var acceptedFiles = accept.map(function (i) {
      return i.toLowerCase();
    });
    if (validateUploadedImage) {
      var validationError = validateUploadedImage(files.addedFiles[0]);
      if (validationError) {
        setError(validationError);
        return;
      }
    }
    if (files.addedFiles[0].size > maxFileSizeInBytes) {
      setError(i18n.fileTooLarge);
    } else if (acceptedFiles.includes(files.addedFiles[0].name.match(/([^/.]*?)(?=\?|#|$)/ || [])[0].toLowerCase())) {
      var fR = new FileReader();
      fR.readAsDataURL(files.addedFiles[0]);
      fR.onloadend = function (event) {
        onUpload({
          files: files,
          dataURL: event.target.result
        });
      };
      fR.onerror = function (e) {
        setError(e.message);
      };
    } else {
      setError(i18n.wrongFileType(accept));
    }
  };
  var handleErrorClose = function handleErrorClose() {
    setError(false);
  };
  return /*#__PURE__*/React__default.createElement("div", {
    "data-testid": testId,
    className: classnames("".concat(iotPrefix, "--image-uploader"), _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--image-uploader__medium"), other.width >= 252 && other.width <= 519), "".concat(iotPrefix, "--image-uploader__mediumwide"), other.width >= 520 && other.height !== 576), "".concat(iotPrefix, "--image-uploader__large"), other.width >= 520 && other.width <= 1055 && other.height >= 576), "".concat(iotPrefix, "--image-uploader__largewide"), other.width >= 1056 && other.height >= 576), "".concat(iotPrefix, "--image-uploader__url"), fromURL))
  }, error ? /*#__PURE__*/React__default.createElement(InlineNotification, {
    onCloseButtonClick: handleErrorClose,
    kind: "error",
    title: i18n.errorTitle,
    subtitle: error,
    "data-testid": "".concat(testId, "-error-notification")
  }) : fromURL ? /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-url-wrapper")
  }, /*#__PURE__*/React__default.createElement(TextInput, {
    id: "".concat(iotPrefix, "--image-uploader-url-input"),
    ref: imgRef,
    labelText: "",
    placeholder: i18n.urlInput,
    "data-testid": "".concat(testId, "-url-input")
  }), /*#__PURE__*/React__default.createElement(Button, {
    size: buttonSize,
    onClick: handleUploadByURL
    // TODO: pass testId in v3 to override defaults
    // testId={`${testId}-url-upload-button`}
  }, i18n.uploadByURLButton), /*#__PURE__*/React__default.createElement(Button, {
    size: buttonSize,
    onClick: handleCancelFromURLClick,
    kind: "ghost"
    // TODO: pass testId in v3 to override defaults
    // testId={`${testId}-url-cancel-button`}
  }, i18n.uploadByURLCancel)) : /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement(FileUploaderDropContainer, {
    size: "md",
    labelText: "",
    onAddFiles: handleOnChange,
    "data-testid": "".concat(testId, "-file-drop-container")
  }), /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-icon")
  }, /*#__PURE__*/React__default.createElement(Image, {
    size: 32
  })), /*#__PURE__*/React__default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-content")
  }, /*#__PURE__*/React__default.createElement("h2", {
    className: "".concat(iotPrefix, "--image-uploader-drop-label-text")
  }, i18n.dropContainerLabelText), /*#__PURE__*/React__default.createElement("p", {
    className: "".concat(iotPrefix, "--image-uploader-drop-description-text")
  }, i18n.dropContainerDescText), /*#__PURE__*/React__default.createElement(Button, {
    size: buttonSize,
    onClick: onBrowseClick,
    kind: "tertiary"
    // TODO: pass testId in v3 to override defaults
    // testId={`${testId}-browse-button`}
  }, i18n.browseImages), hasInsertFromUrl ? /*#__PURE__*/React__default.createElement(Button, {
    size: buttonSize,
    onClick: handleFromURLClick,
    kind: "tertiary"
    // TODO: pass testId in v3 to override defaults
    // testId={`${testId}-insert-from-url-button`}
  }, i18n.insertUrl) : null)));
};
ImageUploader.propTypes = propTypes;
ImageUploader.defaultProps = defaultProps;
ImageUploader.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "ImageUploader",
  "props": {
    "accept": {
      "defaultValue": {
        "value": "['APNG', 'AVIF', 'GIF', 'JPEG', 'JPG', 'PNG', 'WebP']",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "string"
        }
      },
      "required": false
    },
    "maxFileSizeInBytes": {
      "defaultValue": {
        "value": "1048576",
        "computed": false
      },
      "description": "the maximum file size in bytes",
      "type": {
        "name": "number"
      },
      "required": false
    },
    "validateUploadedImage": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "a callback invoked with the image information, if you want to fail validation return a string with the error",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "onBrowseClick": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "onUpload": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "hasInsertFromUrl": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  dropContainerLabelText: 'Drag file here or click to upload file',\n  dropContainerDescText:\n    'Max file size is 1MB. Supported file types are: APNG, AVIF, GIF, JPEG, PNG, WebP',\n  uploadByURLCancel: 'Cancel',\n  uploadByURLButton: 'OK',\n  browseImages: 'Add from gallery',\n  insertUrl: 'Insert from URL',\n  urlInput: 'Type or insert URL',\n  errorTitle: 'Upload error: ',\n  fileTooLarge: 'Image file is too large',\n  wrongFileType: (accept) =>\n    `This file is not one of the accepted file types, ${accept.join(', ')}`,\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "dropContainerLabelText": {
            "name": "string",
            "required": false
          },
          "dropContainerDescText": {
            "name": "string",
            "required": false
          },
          "uploadByURLCancel": {
            "name": "string",
            "required": false
          },
          "uploadByURLButton": {
            "name": "string",
            "required": false
          },
          "browseImages": {
            "name": "string",
            "required": false
          },
          "insertUrl": {
            "name": "string",
            "required": false
          },
          "urlInput": {
            "name": "string",
            "required": false
          },
          "fileTooLarge": {
            "name": "string",
            "required": false
          },
          "wrongFileType": {
            "name": "func",
            "required": false
          },
          "errorTitle": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'image-uploader'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    }
  }
};
var ImageUploader$1 = ImageUploader;

export { ImageUploader$1 as default };
