"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var image_upload_exports = {};
__export(image_upload_exports, {
  ImageUpload: () => ImageUpload
});
module.exports = __toCommonJS(image_upload_exports);
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_react_measure = require("react-measure");
var import_image_utils = require("./../../../wix-rich-content-common/lib/image-utils.js");
var import_loader_icon = require("../../assets/icons/loader-icon.js");
var import_replace_icon = require("../../assets/icons/replace-icon.js");
var import_defaults = require("../../defaults.js");
var import_helpers = require("../../helpers.js");
var import_rce_helpers_context = require("../rce-helpers-context/index.js");
var import_image_upload_scss = __toESM(require("./image-upload-scss.js"));
var import_types = require("./types.js");
class ImageUploadComponent extends import_react.PureComponent {
  constructor() {
    super(...arguments);
    this.state = {
      value: this.props.value || (0, import_helpers.getRandomValue)(import_defaults.POLL_IMAGES_POOL),
      backgroundImage: null,
      loading: false
    };
    this.$label = import_react.default.createRef();
    this.handleFileUpload = ({ data }) => {
      this.setState(
        {
          value: `https://static.wixstatic.com/media/${data.file_name}`,
          loading: false
        },
        () => {
          this.updateBackgroundImage();
          setTimeout(() => this.sync());
        }
      );
    };
    this.handleFileReadLoad = (backgroundImage, file) => {
      this.setState({ backgroundImage: `url(${backgroundImage})`, loading: false });
      this.setState({ loading: true });
      this.props.rce.handleFileUpload(file, this.handleFileUpload);
    };
    this.handleInputChange = (e) => {
      this.handleFileChange(Array.from(e.target.files));
      e.target.value = null;
    };
    this.handleFileChange = ([file]) => {
      const reader = new FileReader();
      this.setState({ loading: true });
      reader.onload = (e) => this.handleFileReadLoad(e.target.result, file);
      reader.readAsDataURL(file);
    };
    this.handleKeyPress = (e) => {
      const enterOrSpace = e.key === "Enter" || e.key === " " || e.key === "Spacebar" || e.which === 13 || e.which === 32;
      if (enterOrSpace) {
        e.preventDefault();
        this.$label.current?.click();
      }
    };
    this.handleFocus = (e) => {
      e.stopPropagation();
      const { rce } = this.props;
      rce.setInPluginEditingMode(true);
    };
    this.handleBlur = () => {
      const { rce } = this.props;
      rce.setInPluginEditingMode(false);
    };
  }
  componentWillReceiveProps(props) {
    const { value, contentRect } = props;
    const { value: prevValue, contentRect: prevContentRect } = this.props;
    if (value !== prevValue) {
      this.setState({ value }, () => this.updateBackgroundImage());
    }
    if (JSON.stringify(contentRect.bounds) !== JSON.stringify(prevContentRect.bounds)) {
      this.updateBackgroundImage(contentRect.bounds);
    }
  }
  sync() {
    this.props.onChange(this.state.value);
  }
  updateBackgroundImage(bounds = this.props.contentRect.bounds) {
    const { value } = this.state;
    if (!bounds.width || !bounds.height) {
      return null;
    }
    const backgroundImage = `url(${(0, import_image_utils.getScaleImageSrc)(value, bounds.width, bounds.height)})`;
    this.setState(() => ({
      backgroundImage
    }));
  }
  render() {
    const { dataHook, className, rce, small, disabled, measureRef, style = {} } = this.props;
    const { loading, backgroundImage } = this.state;
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        ref: measureRef,
        className: (0, import_classnames.default)(import_image_upload_scss.default.container, className, {
          [import_image_upload_scss.default.disabled]: rce.isViewMode || disabled
        }),
        style: { ...style, backgroundImage },
        tabIndex: rce.isViewMode ? -1 : 0,
        "aria-hidden": rce.isViewMode,
        role: "button",
        onFocus: this.handleFocus,
        onBlur: this.handleBlur,
        onKeyPress: this.handleKeyPress,
        "data-hook": dataHook
      },
      /* @__PURE__ */ import_react.default.createElement("label", { ref: this.$label }, /* @__PURE__ */ import_react.default.createElement(
        "input",
        {
          type: "file",
          disabled: rce.isViewMode || disabled,
          onChange: this.handleInputChange,
          accept: "image/*",
          tabIndex: -1,
          className: import_image_upload_scss.default.imageInput
        }
      ), /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: (0, import_classnames.default)(import_image_upload_scss.default.overlay, {
            [import_image_upload_scss.default.shown]: loading
          })
        },
        loading ? /* @__PURE__ */ import_react.default.createElement(
          import_loader_icon.LoaderIcon,
          {
            width: small ? 24 : 48,
            height: small ? 24 : 48,
            className: import_image_upload_scss.default.spinner
          }
        ) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_replace_icon.ReplaceIcon, null), /* @__PURE__ */ import_react.default.createElement(
          "p",
          {
            className: (0, import_classnames.default)(import_image_upload_scss.default.text, {
              [import_image_upload_scss.default.hide]: small
            })
          },
          "Change Image"
        ))
      ))
    );
  }
}
ImageUploadComponent.propTypes = {
  ...import_types.ImageUploadPropTypes,
  ...import_rce_helpers_context.RCEHelpersPropTypes
};
ImageUploadComponent.defaultProps = {
  imagesPool: [],
  disabled: false
};
const ImageUpload = (0, import_react_measure.withContentRect)("bounds")((0, import_rce_helpers_context.withRCEHelpers)(ImageUploadComponent));
//# sourceMappingURL=image-upload.js.map
