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

export class CommonList extends React.Component {
    static defaultProps = {
        isBlocked: false,
        emptyListText: null,
        noResultsText: 'TRANSLATE:NO_RESULTS',
        blockedText: 'TRANSLATE:PLEASE_WAIT_WHILE_LOADING'
    };

    static propTypes = {
        isBlocked: PropTypes.bool,
        emptyListText: PropTypes.node,
        noResultsText: PropTypes.node,
        blockedText: PropTypes.string
    };

    rowClickHandler(fn) {
        return event => {
            let isInsideStopper = false;
            let currentNode = event.target;
            let rootNode = event.currentTarget;
            let stopperAttribute;

            while (currentNode && currentNode !== rootNode) {
                stopperAttribute = currentNode.dataset
                    ? currentNode.dataset.stopRowClick
                    : currentNode.getAttribute('data-stop-row-click'); // for IE <= 10

                isInsideStopper = String(stopperAttribute).toLowerCase() === 'true';
                if (isInsideStopper) {
                    break;
                } else {
                    currentNode = currentNode.parentNode;
                }
            }

            if (isInsideStopper) {
                event.stopPropagation();
            } else {
                fn(event);
            }
        };
    }

    renderEmpty() {
        return this.props.noResultsText;
    }

    renderEmptyListMessage() {
        if (!this.isEmptyListMessageVisible()) {
            return null;
        }

        const {emptyListText, noResultsText} = this.props;

        if (emptyListText && this.isEmptyList()) {
            return (
                <div className="grid-empty-list-message" data-test-automation-id="emptyListMessage">
                    {emptyListText}
                </div>
            );
        }

        return (
            <div className="grid-empty-list-message" data-test-automation-id="noResultsMessage">
                {noResultsText}
            </div>
        );
    }

    renderBlockedMessage() {
        if (this.props.isBlocked) {
            return (
                <div className="grid-blocked-list-container">
                    <div className="grid-blocked-list-message">{this.props.blockedText}</div>
                </div>
            );
        }
    }

    renderItem() {
        throw new Error('Overwrite renderItem method to use List');
    }

    render() {
        return this.hasItems() ? this.renderItems() : this.renderEmpty();
    }
}
