import { Command } from './Command';
import { AppNodeType } from '../types/node';
import { Edge } from '@xyflow/react';

/**
 * Command to delete a node from the canvas
 */
export class DeleteNodeCommand implements Command {
    private nodeId: string;
    private deletedNode: AppNodeType | null = null;
    private deletedEdges: Edge[] = [];
    private setNodes: (updater: (nodes: AppNodeType[]) => AppNodeType[]) => void;
    private setEdges: (updater: (edges: Edge[]) => Edge[]) => void;
    private getNodes: () => AppNodeType[];
    private getEdges: () => Edge[];

    constructor(
        nodeId: string,
        setNodes: (updater: (nodes: AppNodeType[]) => AppNodeType[]) => void,
        setEdges: (updater: (edges: Edge[]) => Edge[]) => void,
        getNodes: () => AppNodeType[],
        getEdges: () => Edge[]
    ) {
        this.nodeId = nodeId;
        this.setNodes = setNodes;
        this.setEdges = setEdges;
        this.getNodes = getNodes;
        this.getEdges = getEdges;
    }

    execute(): void {
        const nodes = this.getNodes();
        const edges = this.getEdges();
        
        // Store the node and connected edges for undo
        this.deletedNode = nodes.find(n => n.id === this.nodeId) || null;
        this.deletedEdges = edges.filter(e => e.source === this.nodeId || e.target === this.nodeId);
        
        // 删除 node and connected edges
        this.setNodes((nodes) => nodes.filter(n => n.id !== this.nodeId));
        this.setEdges((edges) => edges.filter(e => e.source !== this.nodeId && e.target !== this.nodeId));
    }

    undo(): void {
        if (this.deletedNode) {
            this.setNodes((nodes) => [...nodes, this.deletedNode!]);
        }
        if (this.deletedEdges.length > 0) {
            this.setEdges((edges) => [...edges, ...this.deletedEdges]);
        }
    }

    getDescription(): string {
        return `Delete node: ${this.nodeId}`;
    }
}
