import * as React from "react";
import { useFilterContext } from "./FilterContext";
export const useFilterElement = ({ property, displayStrategy, dependsOn, }) => {
    const filterContext = useFilterContext();
    if (filterContext === undefined) {
        throw new Error("WithFilter requires a Filter Component as an ancestor.");
    }
    const [state, setState] = React.useState({
        selectedValue: undefined,
        values: [],
    });
    React.useEffect(() => {
        const newState = {
            selectedValue: filterContext.getCurrentValue(property),
            values: [],
        };
        if (displayStrategy === "invalidAsDisabled") {
            const propertyCollection = filterContext.getAllValues(property, dependsOn);
            const availableProperties = filterContext.getValues(property);
            newState.values = propertyCollection.map(value => ({
                value,
                disabled: !availableProperties.find(val => val === value),
            }));
        }
        else if (displayStrategy === "all") {
            newState.values = filterContext
                .getAllValues(property)
                .map(value => ({ value }));
        }
        else {
            newState.values = filterContext
                .getValues(property)
                .map(value => ({ value }));
        }
        setState(newState);
    }, [displayStrategy, property, dependsOn, filterContext]);
    const handleChange = (newValue) => {
        if (filterContext.configuration[property] === newValue) {
            return;
        }
        filterContext.setValue(property, newValue);
    };
    return {
        ...state,
        onChange: handleChange,
    };
};
export default (mapElementStateToProps = props => props) => (component) => function WithFilter(props) {
    const { property, displayStrategy, dependsOn, ...childProps } = props;
    const filterElement = useFilterElement({
        property,
        displayStrategy,
        dependsOn,
    });
    return React.createElement(component, {
        ...childProps,
        ...mapElementStateToProps(filterElement, childProps),
    });
};
