import * as React from "react";
import { withSessionContext } from "./SessionContext";
class PropertySubscription extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = this.buildState();
    }
    render() {
        if (this.state === null) {
            return null;
        }
        return this.props.children(this.state);
    }
    componentDidMount() {
        this.update();
        this.subscription = this.props.session.on("ItemConfigured", () => this.update());
    }
    componentWillUnmount() {
        if (this.subscription) {
            this.subscription.destroy();
        }
    }
    componentDidUpdate(prevProps) {
        if (prevProps.propertyKey !== this.props.propertyKey) {
            this.update();
        }
    }
    update() {
        this.setState(this.buildState());
    }
    buildState() {
        const property = this.props.session.getArticleProperty(this.props.comId, this.props.propertyKey);
        if (property === undefined) {
            throw new Error(`Can not get unknown property "${this.props.propertyKey}" for "${this.props.comId}"`);
        }
        const propertyKey = this.props.propertyKey;
        return {
            ...property,
            Values: this.props.createValues(property),
            setPropValue: newValue => this.props.session.changeArticleProperty(this.props.comId, propertyKey, newValue),
        };
    }
}
PropertySubscription.defaultProps = {
    createValues: ({ Values }) => Values.filter(value => value.Visible !== false),
};
const DecoratedSubscription = withSessionContext(PropertySubscription);
export default DecoratedSubscription;
export const withPropertySubscription = (Component) => ({ comId, propertyKey, createValues, ...childProps }) => (React.createElement(DecoratedSubscription, { comId: comId, propertyKey: propertyKey, createValues: createValues }, ({ setPropValue, ...property }) => (
//@ts-ignore
React.createElement(Component, Object.assign({}, childProps, { setPropValue: setPropValue, property: property })))));
