'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.join.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.function.name.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/es.string.match.js');
var React = require('react');
var PropTypes = require('prop-types');
var react = require('@carbon/react');
var classnames = require('classnames');
var Settings = require('../../constants/Settings.js');
var Button = require('../Button/Button.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["hasInsertFromUrl", "onBrowseClick", "i18n", "onUpload", "accept", "validateUploadedImage", "maxFileSizeInBytes", "testId"];
var iotPrefix = Settings.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__default.default.arrayOf(PropTypes__default.default.string),
  onBrowseClick: PropTypes__default.default.func,
  onUpload: PropTypes__default.default.func,
  /** the maximum file size in bytes */
  maxFileSizeInBytes: PropTypes__default.default.number,
  hasInsertFromUrl: PropTypes__default.default.bool,
  /** a callback invoked with the image information, if you want to fail validation return a string with the error */
  validateUploadedImage: PropTypes__default.default.func,
  i18n: PropTypes__default.default.shape({
    dropContainerLabelText: PropTypes__default.default.string,
    dropContainerDescText: PropTypes__default.default.string,
    uploadByURLCancel: PropTypes__default.default.string,
    uploadByURLButton: PropTypes__default.default.string,
    browseImages: PropTypes__default.default.string,
    insertUrl: PropTypes__default.default.string,
    urlInput: PropTypes__default.default.string,
    fileTooLarge: PropTypes__default.default.string,
    wrongFileType: PropTypes__default.default.func,
    errorTitle: PropTypes__default.default.string
  }),
  testId: PropTypes__default.default.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__default.default(_ref, _excluded);
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    fromURL = _useState2[0],
    setFromURL = _useState2[1];
  var _useState3 = React.useState(null),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    error = _useState4[0],
    setError = _useState4[1];
  var _useState5 = React.useState('default'),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    buttonSize = _useState6[0],
    setButtonSize = _useState6[1];
  var imgRef = React.useRef(null);
  React.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;
    }
    cardUtilityFunctions.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.default.createElement("div", {
    "data-testid": testId,
    className: classnames__default.default("".concat(iotPrefix, "--image-uploader"), _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".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.default.createElement(react.InlineNotification, {
    onCloseButtonClick: handleErrorClose,
    kind: "error",
    title: i18n.errorTitle,
    subtitle: error,
    "data-testid": "".concat(testId, "-error-notification")
  }) : fromURL ? /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-url-wrapper")
  }, /*#__PURE__*/React__default.default.createElement(react.TextInput, {
    id: "".concat(iotPrefix, "--image-uploader-url-input"),
    ref: imgRef,
    labelText: "",
    placeholder: i18n.urlInput,
    "data-testid": "".concat(testId, "-url-input")
  }), /*#__PURE__*/React__default.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.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.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(react.FileUploaderDropContainer, {
    size: "md",
    labelText: "",
    onAddFiles: handleOnChange,
    "data-testid": "".concat(testId, "-file-drop-container")
  }), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-icon")
  }, /*#__PURE__*/React__default.default.createElement(iconsReact.Image, {
    size: 32
  })), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(iotPrefix, "--image-uploader-content")
  }, /*#__PURE__*/React__default.default.createElement("h2", {
    className: "".concat(iotPrefix, "--image-uploader-drop-label-text")
  }, i18n.dropContainerLabelText), /*#__PURE__*/React__default.default.createElement("p", {
    className: "".concat(iotPrefix, "--image-uploader-drop-description-text")
  }, i18n.dropContainerDescText), /*#__PURE__*/React__default.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.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;

module.exports = ImageUploader$1;
