import React from 'react';
import PropTypes from 'prop-types';
import { VisualizationProvider } from 'redhotmagma-visualization/VisualizationProvider';
import { AlignTargetProvider } from 'redhotmagma-visualization/AlignTargetProvider';
import { Services } from 'App/ServiceLocator';

export class DefaultVisualizationProvider extends React.Component {
    static propTypes = {
        children: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.node), PropTypes.node]),
    };

    state = {
        visualization: null,
    };

    componentDidMount() {
        const visualization = Services.visualization.getComponent();
        this.setState({
            visualization,
        });
        this.removeComponentChangeListener = Services.visualization.registerComponentChangeListener(
            this.onComponentChange
        );
    }

    componentWillUnmount() {
        this.removeComponentChangeListener && this.removeComponentChangeListener();
    }

    onComponentChange = ({ data: { component } }) => {
        this.setState({ visualization: component });
    };

    render() {
        const { children } = this.props;
        const { visualization } = this.state;
        return (
            <VisualizationProvider visualization={visualization}>
                <AlignTargetProvider>{children}</AlignTargetProvider>
            </VisualizationProvider>
        );
    }
}
