import { v4 as uuidv4 } from 'uuid';
import { getUniqueName } from '../../../utils/get-unique-name';
import { addValues } from '..';
import { SCENE_PATH_LENGTH } from '../../../consts/paths';
const updateIds = (actor) => {
    var _a;
    actor.id = uuidv4();
    (_a = actor.children) === null || _a === void 0 ? void 0 : _a.forEach(updateIds);
};
const getActorDuplicate = (actor, parent) => {
    const duplicate = structuredClone(actor);
    duplicate.name = getUniqueName(duplicate.name, parent);
    updateIds(duplicate);
    return duplicate;
};
const getSceneDuplicate = (scene, parent) => {
    const duplicate = structuredClone(scene);
    duplicate.name = getUniqueName(duplicate.name, parent);
    duplicate.id = uuidv4();
    duplicate.actors.forEach(updateIds);
    return duplicate;
};
const isPathCorrect = (path, isActorDestination) => {
    if (isActorDestination) {
        return path.length > SCENE_PATH_LENGTH;
    }
    return path.length === SCENE_PATH_LENGTH;
};
export const copyByPaths = (sourcePaths, destinationPath) => (dispatch, getState) => {
    const isActorDestination = destinationPath.at(-1) !== 'scenes';
    const destination = getState(destinationPath);
    if (!Array.isArray(destination)) {
        return;
    }
    const { values } = sourcePaths.reduce((acc, path) => {
        if (!isPathCorrect(path, isActorDestination)) {
            return acc;
        }
        const value = getState(path);
        if (value) {
            const duplicate = isActorDestination
                ? getActorDuplicate(value, acc.parent)
                : getSceneDuplicate(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));
    }
};
