import React from 'react';
import PropTypes from 'prop-types';

import {highlight} from '../utils';
import {Highlighter, HIGHLIGHT_TYPE} from '../../Highlighter';

type ListHighlightMode = 'BACKGROUND' | 'BOLD';

export type CommonListHighlightProps = {
    children?: React.ReactNode;
    title?: string;
    textHighlightPattern?: RegExp;
    textFilterPattern?: RegExp;
    listHighlightType?: ListHighlightMode;
    containsRichText?: boolean;
} & Partial<CommonListHighlightDefaultProps>;

export type CommonListHighlightDefaultProps = {
    listHighlightType: ListHighlightMode;
    containsRichText: boolean;
};

export class CommonListHighlight<P extends CommonListHighlightProps> extends React.Component<P> {
    static HIGHLIGHT_TYPE_BACKGROUND = HIGHLIGHT_TYPE.BACKGROUND;
    static HIGHLIGHT_TYPE_BOLD = HIGHLIGHT_TYPE.BOLD;

    static propTypes = {
        children: PropTypes.node,
        title: PropTypes.string,
        textHighlightPattern: PropTypes.object,
        textFilterPattern: PropTypes.object,
        listHighlightType: PropTypes.oneOf([HIGHLIGHT_TYPE.BACKGROUND, HIGHLIGHT_TYPE.BOLD]),
        containsRichText: PropTypes.bool
    };

    static defaultProps = {
        children: null,
        title: null,
        textHighlightPattern: null,
        textFilterPattern: null,
        listHighlightType: HIGHLIGHT_TYPE.BOLD,
        containsRichText: false
    };

    render() {
        const {
            listHighlightType,
            containsRichText,
            title,
            textHighlightPattern,
            textFilterPattern
        } = this.props;

        if (containsRichText || listHighlightType === HIGHLIGHT_TYPE.BACKGROUND) {
            return (
                <Highlighter
                    title={title}
                    listHighlightType={listHighlightType}
                    highlightRegexp={textHighlightPattern}
                    filterRegexp={textFilterPattern}>
                    {this.props.children}
                </Highlighter>
            );
        }

        return highlight(textFilterPattern as any, this.props.children as any, title);
    }
}
