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

// list of the mounted provider components
const providerList = [];

// store the latest canvas so it can be used as default current state for newly mounted components
let currentCanvas = null;

/**
 * Sets the active canvas for all the providers in the list
 * @param canvas
 */
export const updateProviders = canvas => {
    currentCanvas = canvas;
    for (let providerComponent of providerList) {
        providerComponent.setCanvas(canvas);
    }
};

/**
 * HOC that provides the active canvas to the given Component
 * @param Component
 */
export const withActiveCanvas = Component =>
    class ActiveCanvasProvider extends React.Component {
        static propTypes = {
            children: PropTypes.node,
        };

        state = {
            canvas: currentCanvas,
        };

        componentDidMount() {
            providerList.push(this);
        }

        componentWillUnmount() {
            const idx = providerList.indexOf(this);
            providerList.splice(idx, 1);
        }

        setCanvas = canvas => this.setState({ canvas });

        render() {
            return <Component canvas={this.state.canvas}>{this.props.children}</Component>;
        }
    };
