// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { isValidElement } from 'react';
import PropTypes from 'prop-types';
import { useTranslate } from '../LocaleProvider';
export const isLikeText = node => {
  if (typeof node === 'string') {
    return true;
  }

  if ( /*#__PURE__*/isValidElement(node) && node.type === Translate) {
    const {
      component,
      children
    } = node.props;

    if (component === 'span' && (typeof children === 'string' || typeof children === 'undefined' || children === null)) {
      return true;
    }
  }

  return false;
};
/**
 * `Translate` component.
 * @since 0.0.42
 */

const Translate = ({
  component: Tag,
  content,
  children,
  params,
  unsafe,
  fallback,
  namespace,
  translators,
  ...props
}) => {
  const translate = useTranslate(namespace);
  const key = content || children;
  const translator = translators && translators[key];

  if (translator) {
    if (typeof translator === 'function') {
      return translator(params);
    }

    return translator;
  }

  const message = translate(key, params, fallback);

  if (unsafe) {
    props.dangerouslySetInnerHTML = {
      __html: message
    };
  } else {
    props.children = message;
  }

  return /*#__PURE__*/React.createElement(Tag, props);
};

Translate.propTypes = {
  /**
   * A some prefix for the message key.
   * @since 2.6.0
   */
  namespace: PropTypes.string,

  /**
   * Translatable content or message key.
   * @since 0.0.42
   */
  content: PropTypes.string,

  /**
   * Message params
   * @since 0.0.42
   */
  params: PropTypes.object,

  /**
   * Fallback translation value.
   * @since 0.0.47
   */
  fallback: PropTypes.string,

  /**
   * Component to render as the root element. Useful when rendering a `Translate` as `<option>`.
   * @since 0.0.42
   */
  component: PropTypes.elementType,

  /**
   * A set of translation messages. If the set contains a message key, the component uses an item from the set for rendering.
   * @ignore
   */
  translators: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.func, PropTypes.node])),

  /**
   * @ignore
   */
  unsafe: PropTypes.bool,

  /**
   * @ignore
   */
  children: PropTypes.string
};
Translate.defaultProps = {
  namespace: undefined,
  content: undefined,
  params: undefined,
  component: 'span',
  unsafe: undefined,
  fallback: undefined,
  children: undefined,
  translators: undefined
};
export default Translate;