import cls from "classnames";
import React, { PureComponent } from "react";
import { withContentRect } from "react-measure";
import { getScaleImageSrc } from "./../../../wix-rich-content-common/lib/image-utils.js";
import { LoaderIcon } from "../../assets/icons/loader-icon.js";
import { ReplaceIcon } from "../../assets/icons/replace-icon.js";
import { POLL_IMAGES_POOL } from "../../defaults.js";
import { getRandomValue } from "../../helpers.js";
import { RCEHelpersPropTypes, withRCEHelpers } from "../rce-helpers-context/index.js";
import styles from "./image-upload-scss.js";
import { ImageUploadPropTypes } from "./types.js";
class ImageUploadComponent extends PureComponent {
  constructor() {
    super(...arguments);
    this.state = {
      value: this.props.value || getRandomValue(POLL_IMAGES_POOL),
      backgroundImage: null,
      loading: false
    };
    this.$label = React.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(${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__ */ React.createElement(
      "div",
      {
        ref: measureRef,
        className: cls(styles.container, className, {
          [styles.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__ */ React.createElement("label", { ref: this.$label }, /* @__PURE__ */ React.createElement(
        "input",
        {
          type: "file",
          disabled: rce.isViewMode || disabled,
          onChange: this.handleInputChange,
          accept: "image/*",
          tabIndex: -1,
          className: styles.imageInput
        }
      ), /* @__PURE__ */ React.createElement(
        "div",
        {
          className: cls(styles.overlay, {
            [styles.shown]: loading
          })
        },
        loading ? /* @__PURE__ */ React.createElement(
          LoaderIcon,
          {
            width: small ? 24 : 48,
            height: small ? 24 : 48,
            className: styles.spinner
          }
        ) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ReplaceIcon, null), /* @__PURE__ */ React.createElement(
          "p",
          {
            className: cls(styles.text, {
              [styles.hide]: small
            })
          },
          "Change Image"
        ))
      ))
    );
  }
}
ImageUploadComponent.propTypes = {
  ...ImageUploadPropTypes,
  ...RCEHelpersPropTypes
};
ImageUploadComponent.defaultProps = {
  imagesPool: [],
  disabled: false
};
const ImageUpload = withContentRect("bounds")(withRCEHelpers(ImageUploadComponent));
export {
  ImageUpload
};
//# sourceMappingURL=image-upload.js.map
