import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import {isAutomationTestActive} from '../utils/functions';

export class PrintArea extends React.Component {
    static propTypes = {
        id: PropTypes.string.isRequired,
        children: PropTypes.node.isRequired,
        wide: PropTypes.bool
    };

    static defaultProps = {
        wide: true
    };

    static areas = {};

    static print(id) {
        let element = PrintArea.areas[id];
        if (!element) {
            throw new Error(`PrintArea with id "${id}" not found`);
        }
        let node = ReactDOM.findDOMNode(element);
        if (!node) {
            throw new Error(`PrintArea with id "${id}" not found`);
        }
        if (!PrintArea.container) {
            PrintArea.container = document.createElement('div');
            PrintArea.container.setAttribute('data-test-automation-id', 'printArea');
            PrintArea.container.className = classnames('rc-print-area', {
                'rc-print-area-wide': element.props.wide
            });
            document.body.appendChild(PrintArea.container);
        }
        PrintArea.container.innerHTML = PrintArea.getNodeTreeHTML(node);
        if (!isAutomationTestActive()) {
            window.print();
        }
    }

    static getNodeTreeHTML(node) {
        let html = node.innerHTML;
        while (node) {
            node = node.parentNode;
            if (node === document.body) {
                break;
            }
            html = `<${node.tagName} class="rc-print-area-parent ${node.className}">${html}</${
                node.tagName
            }>`;
        }
        return html;
    }

    componentDidMount() {
        if (PrintArea.areas[this.props.id]) {
            // eslint-disable-next-line
            console.error(`PrintArea with id "${this.props.id}" is already exists on page`);
        }
        PrintArea.areas[this.props.id] = this;
    }

    componentWillUnmount() {
        delete PrintArea.areas[this.props.id];
    }

    render() {
        return <span>{this.props.children}</span>;
    }
}
