"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermittedValuesSelector = void 0;
const tslib_1 = require("tslib");
const React = tslib_1.__importStar(require("react"));
const Select_1 = require("../../../components/Select");
const runIfNotResolvedIn_1 = require("../../../Utilities/runIfNotResolvedIn");
const AdaptableContext_1 = require("../../AdaptableContext");
const react_1 = require("react");
const PermittedValuesSelector = function (props) {
    const adaptable = (0, AdaptableContext_1.useAdaptable)();
    const [refetchKey, setRefetchKey] = React.useState(0);
    const [isLoading, setIsLoading] = React.useState(true);
    const [options, setOptions] = React.useState([]);
    const searchFilterRef = React.useRef('');
    const [searchValueWasUsedWhenFiltering, setSearchValueWasUsedWhenFiltering] = React.useState(false);
    const dataType = React.useMemo(() => {
        return adaptable.api.columnApi.getColumnDataTypeForColumnId(props.columnId);
    }, [props.columnId]);
    React.useEffect(() => {
        if (!props.columnId) {
            setIsLoading(false);
            return;
        }
        setIsLoading(true);
        (async () => {
            let searchValueUsedInFilterValue = false;
            const currentSearchValue = searchFilterRef.current;
            const distinctColumnValues = await (0, runIfNotResolvedIn_1.runIfNotResolvedIn)(
            // we are here ALWAYS getting Filter values but sometimes we want to get other things!!!
            props.loadValues
                ? props.loadValues({
                    get currentSearchValue() {
                        searchValueUsedInFilterValue = true;
                        return currentSearchValue;
                    },
                })
                : adaptable.api.gridApi.internalApi.getDistinctFilterDisplayValuesForColumn({
                    columnId: props.columnId,
                    get currentSearchValue() {
                        searchValueUsedInFilterValue = true;
                        return currentSearchValue;
                    },
                }), () => {
                setIsLoading(true);
            });
            setSearchValueWasUsedWhenFiltering(searchValueUsedInFilterValue);
            setIsLoading(false);
            setOptions(distinctColumnValues);
        })();
    }, [props.columnId, props.loadValues, refetchKey]);
    const isCreatable = (props.allowNewValues && !dataType) || ['text', 'number'].includes(dataType);
    const handleSingleValueChange = (value) => {
        if (isCreatable) {
            // try to convert to correct type, when there is not type, e.g. field
            if (!dataType && typeof value === 'string' && !isNaN(parseFloat(value))) {
                props.onChange(parseFloat(value));
            }
            else if (dataType === 'number') {
                let num = parseFloat(value);
                num = isNaN(num) ? null : num;
                props.onChange(num);
            }
            else {
                props.onChange(value);
            }
        }
        else {
            props.onChange(value);
        }
    };
    const handleMultiValueChange = (values) => {
        if (isCreatable) {
            if (dataType === 'number') {
                const nums = values.map((v) => parseFloat(v)).filter((v) => !isNaN(v));
                props.onChange(nums);
            }
            else {
                props.onChange(values);
            }
        }
        else {
            props.onChange(values);
        }
    };
    const handleOnChange = (value) => {
        // convert numbers
        if (props.isMulti) {
            handleMultiValueChange(value);
        }
        else {
            handleSingleValueChange(value);
        }
    };
    const reload = (0, react_1.useCallback)(() => {
        setRefetchKey((k) => k + 1);
    }, []);
    const onInputChange = (value) => {
        searchFilterRef.current = value;
        if (searchValueWasUsedWhenFiltering) {
            reload();
        }
    };
    return (React.createElement(Select_1.Select, { menuPortalTarget: props.menuPortalTarget, size: props.size, isMulti: props.isMulti, className: props.className, disabled: props.disabled, closeMenuOnSelect: !props.isMulti, "data-name": "permitted-values-selector", placeholder: props.placeholder || (props.allowNewValues ? 'Select or type new value' : 'Select value'), isCreatable: isCreatable, isClearable: true, onMenuOpen: reload, options: options, isLoading: isLoading, onInputChange: onInputChange, onChange: handleOnChange, onFocus: props.onFocus, onBlur: props.onBlur, value: props.value }));
};
exports.PermittedValuesSelector = PermittedValuesSelector;
