/*!
 * Copyright (c) Microsoft. All rights reserved.
 * Licensed under the MIT license. See LICENSE file in the project.
 */ import { readStep, Workflow } from '@datashaper/workflow';
import isArray from 'lodash-es/isArray.js';
import { useCallback, useEffect, useState } from 'react';
export function useWorkflow(input, inputs) {
    const [workflow, setWorkflow] = useState(()=>new Workflow(input?.toSchema()));
    // this effect should fire when a new workflow json is uploaded
    useEffect(function resetWorkflowWhenWorkflowChanges() {
        setWorkflow(new Workflow(input?.toSchema()));
    }, [
        input
    ]);
    useEffect(function syncDataTablesWhenInputsChange() {
        if (inputs) {
            workflow.addInputTables(inputs);
        }
    }, [
        workflow,
        inputs
    ]);
    return workflow;
}
/**
 * Returns a hook to generate a new table name based on the given input e.g.
 * "join" could result in "join 1" or "join 2" depending on how many collisions
 *  occur.
 * @param workflow - the workflow instance
 * @returns a safe output name to use
 */ export function useCreateTableId(workflow) {
    return useCallback((name)=>workflow.suggestOutputName(name), [
        workflow
    ]);
}
/**
 * Returns a hook to generate a new table name based on the given input e.g.
 * "join" could result in "join 1" or "join 2" depending on how many collisions
 *  occur.
 * @param workflow - the workflow instance
 * @returns a safe output name to use
 */ export function useCreateTableName(workflow) {
    return useCallback((name)=>workflow.suggestOutputName(name), [
        workflow
    ]);
}
export function useFormattedColumnArg() {
    return useCallback((stepArgs, newName = 'New column')=>{
        const args = stepArgs;
        Object.keys(args).forEach((key)=>{
            if (key === 'to' && !isArray(args[key])) {
                args[key] = newName;
            }
        });
        return args;
    }, []);
}
export function useResetArgs() {
    return useCallback((step)=>{
        const template = readStep(step).args;
        const args = step.args;
        // rewrite through the proxy for each arg entry
        Object.keys(args).forEach((key)=>{
            args[key] = template[key];
        });
        return step;
    }, []);
}
