/**
 * Public wrapper over OverlayStack.Provider and OverlayStack.Consumer
 *
 * Provides data about the layer stack, but hides methods for changing it.
 */
import * as React from 'react';

import {OverlayStack} from './OverlayStack';
import {BodySynchronizer} from '../synchronizer/body_synchronizer/BodySynchronizer';

interface IProps extends React.HTMLAttributes<HTMLDivElement> {

}

class Consumer extends React.PureComponent<{children: (obj: any) => React.ReactNode}> {
    override render () {
        return (
            <OverlayStack.Consumer>
                {(overlayStack) => {
                    if (overlayStack === null) {
                        throw new Error(`Can't find Overlays.Provider in parents.`);
                    }

                    const {stack} = overlayStack;
                    const hasOverlays = Boolean(stack.length);
                    const hasBackdropOverlays = Boolean(stack.filter(({hasBackdrop}) => hasBackdrop).length);

                    return this.props.children({overlayStack: stack, hasOverlays, hasBackdropOverlays});
                }}
            </OverlayStack.Consumer>
        );
    }
}

class Provider extends React.PureComponent<IProps> {
    override render () {
        return (
            <OverlayStack.Provider>
                <Consumer>
                    {({hasOverlays, hasBackdropOverlays}) => (
                        <BodySynchronizer
                            hasOverlays={hasOverlays}
                            hasBackdropOverlays={hasBackdropOverlays}
                        />
                    )}
                </Consumer>
                {this.props.children}
            </OverlayStack.Provider>
        );
    }
}

export const Overlays = {
    Provider,
    Consumer
};
