import { Node, Edge } from '@vue-flow/core';

const STORAGE_KEY = 'topo_graph_data';

interface TopoData {
  nodes: Node[];
  edges: Edge[];
  timestamp: string;
}

/**
 * 拓扑图本地存储Hook
 * 自动保存和加载拓扑图的节点和边数据
 */
export function useTopoStorage() {
  // 保存到本地存储
  const saveTopoData = (nodes: Node[], edges: Edge[]) => {
    try {
      const data: TopoData = {
        nodes,
        edges,
        timestamp: new Date().toISOString(),
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
      console.log('拓扑图数据已保存到本地', data.timestamp);
    } catch (error) {
      console.error('保存拓扑图数据失败:', error);
    }
  };

  // 从本地存储加载
  const loadTopoData = (): TopoData | null => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) {
        const data = JSON.parse(stored) as TopoData;
        console.log('从本地加载拓扑图数据', data.timestamp);
        return data;
      }
    } catch (error) {
      console.error('加载拓扑图数据失败:', error);
    }
    return null;
  };

  // 清除本地存储
  const clearTopoData = () => {
    try {
      localStorage.removeItem(STORAGE_KEY);
      console.log('已清除本地拓扑图数据');
    } catch (error) {
      console.error('清除拓扑图数据失败:', error);
    }
  };

  return {
    saveTopoData,
    loadTopoData,
    clearTopoData,
  };
}
