import React from 'react';
import {withContextConsumer} from "@formanta/react";

const FeatureManagerContext = React.createContext({});

class FeatureManagerProvider extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
        if(props.features) {
            this.state.features = props.features;
        }

        this.state.changeFeatureSet = (features) => {
            // todo: check if deep-merge wanted/needed
            this.setState({features: {...this.state.features, ...features}});
        };

        this.state.isEnabled = (feature) => {
            return (feature && this.state.features[feature]);
        };

        this.state.isAbilityEnabled = (feature, name) => {
            return (
                feature && name &&
                this.state.features[feature] && this.state.features[feature][name]
            );
        };
    }

    render() {
        return (
            <FeatureManagerContext.Provider value={this.state}>
                {this.props.children}
            </FeatureManagerContext.Provider>
        );
    }
}

const withFeatureManager = withContextConsumer(FeatureManagerContext.Consumer);

export {FeatureManagerProvider, withFeatureManager};