import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
// Copyright 1999-2020. Plesk International GmbH. All rights reserved.
import React, { cloneElement, Component, Fragment } from 'react';
import Layer from '../Layer';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { CLS_PREFIX, Z_INDEX_TOOLTIP } from '../../constants';
import { wrapFunction } from '../utils';

const createRectFactory = (width, height) => (left, top) => ({
  top,
  left,
  right: left + width,
  bottom: top + height
});

const isInside = (r1, r2) => r1.left >= r2.left && r1.right <= r2.right && r1.top >= r2.top && r1.bottom <= r2.bottom;

const determinePosition = ({
  clientX,
  clientY,
  tooltipWidth,
  tooltipHeight,
  targetRect
}) => {
  const X_EXTRA_SPACE = 8;
  const Y_BOTTOM_EXTRA_SPACE = 16;
  const Y_TOP_EXTRA_SPACE = 8;
  const createTooltipRect = createRectFactory(tooltipWidth, tooltipHeight);
  const viewRect = {
    top: 0,
    left: 0,
    right: document.documentElement.clientWidth,
    bottom: document.documentElement.clientHeight
  };
  const positionFns = [// right bottom
  () => ({
    left: clientX + X_EXTRA_SPACE,
    top: clientY + Y_BOTTOM_EXTRA_SPACE
  }), // left bottom
  () => ({
    left: clientX - tooltipWidth - X_EXTRA_SPACE,
    top: clientY + Y_BOTTOM_EXTRA_SPACE
  }), // center bottom
  () => ({
    left: targetRect.left + (targetRect.right - targetRect.left) / 2 - tooltipWidth / 2,
    top: clientY + Y_BOTTOM_EXTRA_SPACE
  }), // right top
  () => ({
    left: clientX + X_EXTRA_SPACE,
    top: clientY - tooltipHeight - Y_TOP_EXTRA_SPACE
  }), // left top
  () => ({
    left: clientX - tooltipWidth - Y_TOP_EXTRA_SPACE,
    top: clientY - tooltipHeight - Y_TOP_EXTRA_SPACE
  }), // center top
  () => ({
    left: targetRect.left + (targetRect.right - targetRect.left) / 2 - tooltipWidth / 2,
    top: clientY - tooltipHeight - Y_BOTTOM_EXTRA_SPACE
  })];

  for (let i = 0; i < positionFns.length; i++) {
    const fn = positionFns[i];
    const {
      left,
      top
    } = fn();
    const tooltipRect = createTooltipRect(left, top);

    if (isInside(tooltipRect, viewRect)) {
      return {
        left: left + window.pageXOffset,
        top: top + window.pageYOffset
      };
    }
  }

  return {
    top: targetRect.top + Y_BOTTOM_EXTRA_SPACE,
    left: targetRect.left + X_EXTRA_SPACE
  };
};
/**
 * `Tooltip` component is used for providing information about an interface element
 * while user hovers the pointer over the element.
 * @since 0.0.35
 */


class Tooltip extends Component {
  constructor(...args) {
    super(...args);

    _defineProperty(this, "state", {
      left: 0,
      top: 0,
      ready: false,
      visible: false
    });

    _defineProperty(this, "handleShow", () => {
      if (this.showTimer) {
        clearTimeout(this.showTimer);
        this.showTimer = null;
      }

      this.setState({
        visible: true
      });
    });

    _defineProperty(this, "handleHide", () => {
      if (this.showTimer) {
        clearTimeout(this.showTimer);
        this.showTimer = null;
      }

      this.setState({
        visible: false,
        ready: false
      });
    });

    _defineProperty(this, "handleMouseEnter", () => {
      if (this.showTimer) {
        return;
      }

      this.setState({
        ready: true
      });
      this.showTimer = setTimeout(() => this.handleShow(), this.props.delay);
    });

    _defineProperty(this, "handleMouseMove", e => {
      // TODO: try to add throttle
      if (this.tooltipEl) {
        const targetRect = e.target.getBoundingClientRect();
        const {
          width: tooltipWidth,
          height: tooltipHeight
        } = this.tooltipEl.getBoundingClientRect();
        const position = determinePosition({
          clientX: e.clientX,
          clientY: e.clientY,
          tooltipWidth,
          tooltipHeight,
          targetRect
        });
        this.setState({ ...position
        });
      }
    });
  }

  componentWillUnmount() {
    clearTimeout(this.showTimer);
  }

  renderTooltip() {
    const {
      baseClassName,
      className,
      children,
      title,
      style,
      delay,
      ...props
    } = this.props;
    const {
      left,
      top,
      visible
    } = this.state;
    return /*#__PURE__*/React.createElement(Layer, {
      level: Z_INDEX_TOOLTIP
    }, /*#__PURE__*/React.createElement("span", _extends({
      ref: el => {
        this.tooltipEl = el;
      },
      className: classNames(baseClassName, className),
      style: { ...style,
        transform: `translate(${left}px, ${top}px)`,
        visibility: visible ? 'visible' : 'hidden'
      },
      role: "tooltip"
    }, props), title));
  }

  render() {
    const {
      ready
    } = this.state;
    return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/cloneElement(this.props.children, {
      onMouseEnter: wrapFunction(this.props.children.props.onMouseEnter, this.handleMouseEnter),
      onMouseMove: wrapFunction(this.props.children.props.onMouseMove, this.handleMouseMove),
      onMouseLeave: wrapFunction(this.props.children.props.onMouseLeave, this.handleHide),
      onMouseDown: wrapFunction(this.props.children.props.onMouseDown, this.handleHide)
    }), ready && this.renderTooltip());
  }

}

Tooltip.propTypes = {
  /**
   * Content of the tooltip
   * @since 0.0.42
   */
  title: PropTypes.node.isRequired,

  /**
   * Show delay (ms)
   * @since 0.0.50
   */
  delay: PropTypes.number,

  /**
   * Element with tooltip
   * @since 0.0.42
   */
  children: PropTypes.element.isRequired,

  /**
   * @ignore
   */
  style: PropTypes.object,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * @ignore
   */
  baseClassName: PropTypes.string
};
Tooltip.defaultProps = {
  delay: 550,
  style: undefined,
  className: undefined,
  baseClassName: `${CLS_PREFIX}tooltip`
};
export default Tooltip;