import React from "react"
import { FiltersMessage } from "../types/filter.type"
import { BodyInputAutocomplete, FilterTextField } from "./style"

export interface BooleanEditorProps {
    value: boolean
    messages: FiltersMessage,
    onChange: (value: boolean) => void,
    onEditting: (editting: boolean) => void,
}

export const BooleanEditor: React.FC<BooleanEditorProps> = ({ value, messages, onChange, onEditting }) => {
    const handleChange = (event: any, value: any) => {
        onChange(!!value);

        event.stopPropagation();
        onEditting(false);
    }

    return (
        <BodyInputAutocomplete
            options={[true, false]}
            getOptionLabel={(option: any) => option ? messages.true : messages.false}
            value={!!value}
            onChange={handleChange}
            renderInput={(params: any) => {
                let endAdornment = params.InputProps.endAdornment as any;
                const adornmentChildren = endAdornment && endAdornment.props && endAdornment.props.children
                    ? endAdornment.props.children
                    : null;

                if (adornmentChildren && Array.isArray(adornmentChildren) && adornmentChildren.length > 0) {
                    endAdornment = adornmentChildren[adornmentChildren.length - 1];
                }
                return (
                    <FilterTextField
                        {...params}
                        focused
                        variant="standard"
                        InputProps={{ ...params.InputProps, autoFocus: true, endAdornment }}
                        onBlur={() => onEditting(false)} />
                )
            }}
        />
    )
}