import { v4 as uuidv4 } from 'uuid';
import { getUniqueName } from '../../../utils/get-unique-name';
import { getIdByPath } from '../../../utils/get-id-by-path';
import { addValues, setValue, deleteByPaths } from '..';
import { getUpdatedScenes, filterScenes } from './utils';
const updateIds = (template) => {
    var _a;
    template.id = uuidv4();
    (_a = template.children) === null || _a === void 0 ? void 0 : _a.forEach(updateIds);
};
const getDuplicate = (template, parent) => {
    const duplicate = structuredClone(template);
    duplicate.name = getUniqueName(duplicate.name, parent);
    updateIds(duplicate);
    return duplicate;
};
export const moveByPaths = (sourcePaths, destinationPath) => (dispatch, getState) => {
    const destination = getState(destinationPath);
    if (!Array.isArray(destination)) {
        return;
    }
    const { values } = sourcePaths.reduce((acc, path) => {
        const value = getState(path);
        if (value) {
            const duplicate = getDuplicate(value, acc.parent);
            acc.values.push(duplicate);
            acc.parent.push(duplicate);
        }
        return acc;
    }, { values: [], parent: destination.slice(0) });
    if (!values.length) {
        return;
    }
    dispatch(addValues(destinationPath, values));
    let scenes = getState(['scenes']);
    if (destinationPath.at(-1) === 'children') {
        const parentTemplateId = getIdByPath(destinationPath.slice(0, -1));
        scenes = getUpdatedScenes(scenes, parentTemplateId, values);
    }
    const templateIds = new Set(sourcePaths.map((path) => getIdByPath(path)));
    scenes = filterScenes(scenes, templateIds);
    dispatch(setValue(['scenes'], scenes, true));
    dispatch(deleteByPaths(sourcePaths, true));
};
