"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var React = require("react");
var FilterContext_1 = require("./FilterContext");
exports.useFilterElement = function (_a) {
    var property = _a.property, displayStrategy = _a.displayStrategy, dependsOn = _a.dependsOn;
    var filterContext = FilterContext_1.useFilterContext();
    if (filterContext === undefined) {
        throw new Error("WithFilter requires a Filter Component as an ancestor.");
    }
    var _b = tslib_1.__read(React.useState({
        selectedValue: undefined,
        values: [],
    }), 2), state = _b[0], setState = _b[1];
    React.useEffect(function () {
        var newState = {
            selectedValue: filterContext.getCurrentValue(property),
            values: [],
        };
        if (displayStrategy === "invalidAsDisabled") {
            var propertyCollection = filterContext.getAllValues(property, dependsOn);
            var availableProperties_1 = filterContext.getValues(property);
            newState.values = propertyCollection.map(function (value) { return ({
                value: value,
                disabled: !availableProperties_1.find(function (val) { return val === value; }),
            }); });
        }
        else if (displayStrategy === "all") {
            newState.values = filterContext
                .getAllValues(property)
                .map(function (value) { return ({ value: value }); });
        }
        else {
            newState.values = filterContext
                .getValues(property)
                .map(function (value) { return ({ value: value }); });
        }
        setState(newState);
    }, [displayStrategy, property, dependsOn, filterContext]);
    var handleChange = function (newValue) {
        if (filterContext.configuration[property] === newValue) {
            return;
        }
        filterContext.setValue(property, newValue);
    };
    return tslib_1.__assign(tslib_1.__assign({}, state), { onChange: handleChange });
};
exports.default = (function (mapElementStateToProps) {
    if (mapElementStateToProps === void 0) { mapElementStateToProps = function (props) { return props; }; }
    return function (component) {
        return function WithFilter(props) {
            var property = props.property, displayStrategy = props.displayStrategy, dependsOn = props.dependsOn, childProps = tslib_1.__rest(props, ["property", "displayStrategy", "dependsOn"]);
            var filterElement = exports.useFilterElement({
                property: property,
                displayStrategy: displayStrategy,
                dependsOn: dependsOn,
            });
            return React.createElement(component, tslib_1.__assign(tslib_1.__assign({}, childProps), mapElementStateToProps(filterElement, childProps)));
        };
    };
});
