import { isNumericInputStep } from '@data-wrangling-components/core';
import { columnTypes, DataType } from '@essex/arquero';
import { NodeInput } from '@essex/dataflow';
import { useCallback, useEffect, useMemo } from 'react';
import { useResetArgs } from '../hooks/common.js';
import { useDropdownChangeHandler, useTextFieldChangeHandler } from '../hooks/fluent.js';
import { selectStepComponent } from '../selectStepComponent.js';
export function useStepChangeHandler(index, onChange) {
    return useCallback((step)=>onChange(step, index), [
        index,
        onChange
    ]);
}
export function useStepArgsComponent(step) {
    return useMemo(()=>step ? selectStepComponent(step) : null, [
        step
    ]);
}
export function useColumnFilter(step, table) {
    const typeMap = useMemo(()=>{
        if (table) {
            return columnTypes(table);
        }
        return {};
    }, [
        table
    ]);
    return useCallback((name)=>{
        return isNumericInputStep(step) ? typeMap[name] === DataType.Number : true;
    }, [
        typeMap,
        step
    ]);
}
export function useInputTableChanged(step, graph, onChange) {
    const resetArgs = useResetArgs();
    return useDropdownChangeHandler(step, (s, val)=>{
        if (val != null) {
            // determine the graph node id to subscribe from
            const tableName = val;
            const outputNode = graph?.outputDefinitions.find((o)=>o.name === tableName)?.node;
            // wire up the Step's input field
            const node = outputNode ?? tableName;
            s.input[NodeInput.Source] = {
                node
            };
            resetArgs(s);
        } else {
            // no value: delete the input
            delete s.input[NodeInput.Source];
        }
    }, onChange);
}
export function useInputColumnChanged(step, onChange) {
    return useDropdownChangeHandler(step, (s, val)=>s.args.column = val, onChange);
}
export function useOutputColumnChanged(step, onChange) {
    return useTextFieldChangeHandler(step, (s, val)=>s.args.to = val, onChange);
}
export function useOutputTableChanged(step, onChangeOutput, onChange) {
    return useTextFieldChangeHandler(step, (_s, val)=>onChangeOutput(val), onChange);
}
export function useDefaultOutputNameInitially(step, output, onChangeOutput) {
    useEffect(()=>{
        onChangeOutput(output ?? step.id);
    }, // eslint-disable-next-line react-hooks/exhaustive-deps
    []);
}
