import * as React from 'react';
import {PropertyFilterSelect} from './PropertyFilterSelect';
import {PropertyFilterMultiSelect} from './PropertyFilterMultiSelect';
import {propertyFieldContext} from './context';
import {PropertyFilterValue} from './types';

type PropertyFilterProps = {
    testAutomationId: string;
    onChange(values: PropertyFilterValue): void;
    values?: PropertyFilterValue;
};

export class PropertyFilter extends React.PureComponent<PropertyFilterProps> {
    static Select = PropertyFilterSelect;
    static MultiSelect = PropertyFilterMultiSelect;

    static contextType = propertyFieldContext;

    static defaultProps = {
        values: {},
        testAutomationId: 'propertyFilter'
    };

    onChange = (id, value) => {
        const nextValue = {
            ...this.props.values,
            [id]: value
        };

        this.props.onChange(nextValue);
    };

    render() {
        const {testAutomationId, values, children} = this.props;
        const {Provider} = propertyFieldContext;
        const contextValue = {
            values,
            onChange: this.onChange
        };

        return (
            <section className="rc-property-filter" data-test-automation-id={testAutomationId}>
                <Provider value={contextValue}>{children}</Provider>
            </section>
        );
    }
}
