/**
 * Configurable tooltip component
 * Now implemented as a layer for the component
 * https://github.com/react-component/tooltip
 *
 * @author Sergey Shishigin
 * @date 2019-07-17
 */

import * as React from 'react';
import {PLACEMENT, POPOVER_BOUNDARIES, POPOVER_THEME, TRIGGER} from '../../constants';
import {IProps as PopoverProps} from '../popover/Popover.types';
import {Popover} from '../popover/Popover';
import * as styles from './tooltip.m.css';

type IProps = Omit<PopoverProps, 'target'> & {
    overlay:  React.ReactNode;
    mouseLeaveDelay: number;
    mouseEnterDelay: number;
    children: React.ReactElement;
}

const defaultProps = {
    placement: PLACEMENT.RIGHT,
    trigger: TRIGGER.HOVER,
    mouseLeaveDelay: 100,
    mouseEnterDelay: 500,
    boundaries: POPOVER_BOUNDARIES.VIEWPORT,
    theme: POPOVER_THEME.DARK
};

export class Tooltip extends React.PureComponent<IProps> {

    static defaultProps = defaultProps;

    override render () {
        const {
            overlay,
            children,
            ...otherProps
        } = this.props;

        if (React.Children.count(children) > 1 || React.Children.count(children) === 0) {
            throw new Error('Could not use tooltip with empty or more then 1 children');
        }

        const target = React.Children.only(children);

        return (
            <Popover
                {...otherProps}
                target={target}
            >
                <div className={styles.tooltipMessage}>
                    {overlay}
                </div>
            </Popover>
        );
    }
}
