"use strict";

exports.__esModule = true;
exports.default = void 0;

var _react = _interopRequireWildcard(require("react"));

var _InputAdornment = _interopRequireDefault(require("@mui/material/InputAdornment"));

var _Icon = _interopRequireDefault(require("@mui/material/Icon"));

var _IconButton = _interopRequireDefault(require("@mui/material/IconButton"));

var _TextField = _interopRequireDefault(require("@mui/material/TextField"));

var _core = require("@selfcommunity/core");

var _Media = require("../../../../constants/Media");

var _reactIntl = require("react-intl");

var _common = _interopRequireDefault(require("../../../../messages/common"));

var _material = require("@mui/material");

const _excluded = ["helperText", "error", "onSuccess"];

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 (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 || 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 _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

const INITIAL_STATE = {
  url: '',
  urlError: null
};

var _default = props => {
  // STATE
  const [isCreating, setIsCreating] = (0, _react.useState)(false);
  const [state, setState] = (0, _react.useState)(Object.assign({}, INITIAL_STATE));
  const {
    url,
    urlError
  } = state; // REFS

  const urlRef = _react.default.useRef(url);

  urlRef.current = url;

  const timerRef = _react.default.useRef(null); // PROPS


  const {
    helperText,
    error,
    onSuccess
  } = props,
        rest = _objectWithoutPropertiesLoose(props, _excluded); // INTL


  const intl = (0, _reactIntl.useIntl)(); // Component update

  (0, _react.useEffect)(() => {
    // Clear the interval when the component unmounts
    return () => clearTimeout(timerRef.current);
  }, []); // HANDLERS

  const handleChange = event => {
    const target = event.target;
    setState({
      url: target.value,
      urlError: _core.UrlUtils.isValidUrl(target.value) ? null : intl.formatMessage(_common.default.urlError)
    });
  };

  const handleSubmit = event => {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }

    timerRef.current && clearTimeout(timerRef.current);
    setIsCreating(true);

    _core.http.request({
      url: _core.Endpoints.ComposerMediaCreate.url(),
      method: _core.Endpoints.ComposerMediaCreate.method,
      data: {
        type: _Media.MEDIA_TYPE_URL,
        url: urlRef.current
      }
    }).then(res => {
      setState(Object.assign({}, INITIAL_STATE));
      onSuccess && onSuccess(res.data);
    }).catch(error => {
      setState(Object.assign({}, (0, _core.formatHttpError)(error), {
        url: urlRef.current
      }));
    }).then(() => setIsCreating(false));
  };

  const handlePaste = event => {
    timerRef.current && clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      if (_core.UrlUtils.isValidUrl(urlRef.current)) {
        handleSubmit(event);
      }
    }, 500);
  };
  /**
   * Renders url text field
   */


  return /*#__PURE__*/_react.default.createElement("form", {
    method: "post",
    onSubmit: handleSubmit
  }, /*#__PURE__*/_react.default.createElement(_TextField.default, _extends({
    value: url,
    type: "url",
    onChange: handleChange,
    onPaste: handlePaste,
    error: error || Boolean(urlError),
    helperText: helperText || urlError || /*#__PURE__*/_react.default.createElement(_reactIntl.FormattedMessage, {
      id: "ui.composer.media.link.add.help",
      defaultMessage: "ui.composer.media.link.add.help"
    }),
    disabled: isCreating
  }, rest, {
    InputProps: {
      endAdornment: /*#__PURE__*/_react.default.createElement(_InputAdornment.default, {
        position: "end"
      }, /*#__PURE__*/_react.default.createElement(_material.Fade, {
        in: urlError === null && url !== ''
      }, /*#__PURE__*/_react.default.createElement(_IconButton.default, {
        size: "small",
        disabled: isCreating,
        type: "submit"
      }, isCreating ? /*#__PURE__*/_react.default.createElement(_material.CircularProgress, {
        color: "primary",
        size: 20
      }) : /*#__PURE__*/_react.default.createElement(_Icon.default, null, "play_arrow"))))
    }
  })));
};

exports.default = _default;