/*!
 * Copyright (c) Microsoft. All rights reserved.
 * Licensed under the MIT license. See LICENSE file in the project.
 */ import { readStep } from '@datashaper/workflow';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCreateTableId, useFormattedColumnArg } from '../hooks/index.js';
export function useHandleSaveClick(step, onTransformRequested) {
    return useCallback(()=>{
        if (step) {
            onTransformRequested?.(step);
        }
    }, [
        onTransformRequested,
        step
    ]);
}
export function useInternalTableStep(step, workflow) {
    const [internal, setInternal] = useState();
    const formattedColumnArg = useFormattedColumnArg();
    useEffect(()=>{
        if (step) {
            setInternal(step);
        }
    }, [
        step,
        setInternal
    ]);
    const createNewTableId = useCreateTableId(workflow);
    const handleVerbChange = useCallback((verb)=>{
        const id = createNewTableId(verb);
        const _step = readStep({
            verb,
            id
        });
        _step.args = formattedColumnArg(_step.args);
        setInternal(_step);
    }, [
        setInternal,
        formattedColumnArg,
        createNewTableId
    ]);
    return {
        internal,
        handleVerbChange,
        setInternal
    };
}
export function useStepOutputHandling(workflow, step) {
    const [output, setOutput] = useState();
    const [initialOutput, setInitialOutput] = useState('');
    useEffect(function useExistingOutputName() {
        if (step?.id && workflow.hasOutputName(step.id)) {
            setOutput(step.id);
        }
    }, [
        workflow,
        step
    ]);
    useEffect(function useOutputNameHasChanged() {
        if (output) {
            setInitialOutput((prev)=>!prev ? output : prev);
        }
    }, [
        output,
        setInitialOutput
    ]);
    return useMemo(()=>({
            output,
            outputHasChanged: output !== initialOutput,
            onOutputChanged: setOutput
        }), [
        output,
        initialOutput,
        setOutput
    ]);
}
