import { v4 as uuidv4 } from 'uuid';
import { getUniqueName } from '../../../../../../../../../utils/get-unique-name';
import { addValues } from '../../../../../../../../commands';
const getStateDuplicate = (state, parent) => {
    const duplicate = structuredClone(state);
    duplicate.id = uuidv4();
    duplicate.name = getUniqueName(duplicate.name, parent);
    if (duplicate.type === 'group') {
        duplicate.substates.forEach((substate) => {
            substate.id = uuidv4();
        });
    }
    return duplicate;
};
const getSubstateDuplicate = (substate, parent) => {
    const duplicate = structuredClone(substate);
    duplicate.id = uuidv4();
    duplicate.name = getUniqueName(duplicate.name, parent);
    return duplicate;
};
const isPathCorrect = (path, isStateDestination) => {
    if (isStateDestination) {
        return path.at(-2) === 'states';
    }
    return path.at(-2) === 'substates';
};
export const copyByPaths = (sourcePaths, destinationPath) => (dispatch, getState) => {
    const isStateDestination = destinationPath.at(-1) === 'states';
    const destination = getState(destinationPath);
    if (!Array.isArray(destination)) {
        return;
    }
    const { values } = sourcePaths.reduce((acc, path) => {
        if (!isPathCorrect(path, isStateDestination)) {
            return acc;
        }
        const value = getState(path);
        if (value) {
            const duplicate = isStateDestination
                ? getStateDuplicate(value, acc.parent)
                : getSubstateDuplicate(value, acc.parent);
            acc.values.push(duplicate);
            acc.parent.push(duplicate);
        }
        return acc;
    }, { values: [], parent: destination.slice(0) });
    if (values.length) {
        dispatch(addValues(destinationPath, values));
    }
};
