import { checkEmpty } from '../checkEmpty/checkEmpty.js';

const getTreeDetails = (action, oldData, newData, sourceId, _deletedIds) => {
    let treeDataList = []; // Initialized to avoid 'used before assigned'
    let root = undefined;
    const findIndexByKey = (data, key) => {
        return data.findIndex((node) => node.key === key);
    };
    const getIndex = () => {
        if (sourceId) {
            const indexByKey = findIndexByKey(oldData, sourceId);
            if (indexByKey === -1) {
                throw new Error(`Key "${sourceId}" not found in oldData.`);
            }
            return indexByKey;
        }
        return 0;
    };
    const tempNewData = [...newData];
    switch (action) {
        case 'above':
        case 'below': {
            const newDataMap = new Map(tempNewData.map((node) => [node.key, node]));
            const consumedNewKeys = new Set();
            const updatedOldData = oldData.map((oldNode) => {
                if (oldNode.key && newDataMap.has(oldNode.key)) {
                    consumedNewKeys.add(oldNode.key);
                    const updatedNode = newDataMap.get(oldNode.key);
                    return {
                        ...updatedNode,
                    };
                }
                return oldNode;
            });
            const brandNewNodes = tempNewData.filter((node) => node.key && !consumedNewKeys.has(node.key));
            treeDataList = (action === 'above'
                ? [...brandNewNodes, ...updatedOldData].slice(0, 100)
                : [...updatedOldData, ...brandNewNodes].slice(-100));
            break;
        }
        case 'expand':
        case 'expandAll':
        case 'collapseAll':
        case 'collapse': {
            const actionIndex = getIndex();
            if (actionIndex === undefined) {
                throw new Error("Both sourceId and index are required for 'expand' or 'collapse' actions.");
            }
            if (actionIndex === 0 &&
                !['above', 'below'].includes(action) &&
                !checkEmpty(tempNewData) &&
                tempNewData[0]) {
                tempNewData[0] = { ...tempNewData[0], lastResource: true };
            }
            treeDataList = [...oldData.slice(0, actionIndex), ...tempNewData];
            break;
        }
        case 'addAbove': {
            const addAboveIndex = getIndex();
            if (addAboveIndex === undefined) {
                throw new Error("Both sourceId and index are required for 'addAbove' action.");
            }
            treeDataList = [
                ...oldData.slice(0, addAboveIndex),
                ...tempNewData,
                ...oldData.slice(addAboveIndex),
            ];
            break;
        }
        case 'addBelow': {
            const addBelowIndex = getIndex();
            if (addBelowIndex === undefined) {
                throw new Error("Both sourceId and index are required for 'addBelow' action.");
            }
            treeDataList = [
                ...oldData.slice(0, addBelowIndex + 1),
                ...tempNewData,
                ...oldData.slice(addBelowIndex + 1),
            ];
            break;
        }
        case 'start':
        case 'show':
        case 'hide':
        case 'clone':
        case 'create':
        case 'refresh':
        case 'delete': {
            if (checkEmpty(tempNewData)) {
                throw new Error('Tree data list is empty, cannot determine root.');
            }
            root = tempNewData[0];
            treeDataList = tempNewData
                .filter((node) => node.key)
                .filter((node) => node.hierarchy !== 0);
            break;
        }
        default:
            throw new Error(`Invalid action: ${action}`);
    }
    if (checkEmpty(treeDataList) &&
        !['start', 'delete', 'hide', 'refresh'].includes(action)) {
        console.warn('Tree data list is empty. Returning default state.');
    }
    const firstNode = treeDataList[0] || root;
    const lastNode = treeDataList[treeDataList.length - 1] || {
        lastResource: true,
        key: '',
    };
    return {
        treeDataList,
        next: !lastNode?.lastResource,
        previous: !firstNode?.lastResource,
        startId: firstNode?.key,
        endId: lastNode?.key,
        root,
    };
};
// NOTE:: This function is used to update the state of the tree nodes based on the current node's state and searchKey.
// from the search key will get all its parent, using this will be updating the container state.
// It returns the updated treeDataList.
const updateTreeState = (treeDataList, currentNode) => {
    const containerIds = currentNode.searchKey?.split('/') || [];
    if (checkEmpty(containerIds)) {
        return treeDataList;
    }
    return treeDataList.map((node) => {
        if (containerIds.includes(node.key)) {
            return { ...node, state: currentNode.state };
        }
        return node;
    });
};

export { getTreeDetails, updateTreeState };
//# sourceMappingURL=getTreeDetails.js.map
