// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   chiayin.kuo@dsp.im (chiayin), 2023/1/31
//   imacat.yang@dsp.im (imacat), 2023/9/23
//   cindy.chang@dsp.im (Cindy Chang), 2024/5/30
/**
 * @module stores/cytoscapeStore Cytoscape node position persistence
 *   store for saving and restoring graph node positions to/from
 *   localStorage.
 */

import { defineStore } from 'pinia';

import { SAVE_KEY_NAME } from '@/constants/constants.js';


export interface Position {
  x: number;
  y: number;
}

export interface Node {
  id: string;
  position: Position;
}

export interface NodePositions {
  [direction: string]: {
    [graphId: string]: Node[];
  }
}


export const useCytoscapeStore = defineStore('cytoscapeStore', {
  state: () => ({
    nodePositions: {} as NodePositions,
    currentGraphId: "",
  }),
  actions: {
    /**
     * Saves or updates the position of a single node.
     * @param {string} nodeId - The node ID.
     * @param {{x: number, y: number}} position - The node position.
     * @param {string} direction - Layout direction ('TB' or 'LR').
     */
    saveNodePosition(nodeId: string, position: Position, direction: string) {
      if (!this.nodePositions[this.currentGraphId]) {
        this.nodePositions[this.currentGraphId] = {};
      }
      if (!this.nodePositions[this.currentGraphId][direction]) {
        this.nodePositions[this.currentGraphId][direction] = [];
      }
      // If this graph's data was previously stored in localStorage
      if (localStorage.getItem(SAVE_KEY_NAME)) {
        const nodeToSave = this.nodePositions[this.currentGraphId][direction]
          .find(node => node.id === nodeId);
        if (nodeToSave) {
          nodeToSave.position = position;
        } else {
          this.nodePositions[this.currentGraphId][direction]
            .push({ id: nodeId, position: position });
        }
      } else {
        this.nodePositions[this.currentGraphId][direction]
          .push({ id: nodeId, position: position });
      }
      this.savePositionsToStorage();
    },
    /**
     * Loads node positions from local storage.
     * @param {string} direction - Layout direction ('TB' or 'LR').
     */
    loadPositionsFromStorage(direction: string) {
      if (!this.nodePositions[this.currentGraphId]) return;
      try {
        const raw = localStorage.getItem(SAVE_KEY_NAME);
        if (raw) {
          const parsed = JSON.parse(raw);
          if (parsed[this.currentGraphId]) {
            this.nodePositions[this.currentGraphId][direction] =
              parsed[this.currentGraphId][direction];
          }
        }
      } catch {
        // Corrupted localStorage data; ignore and use defaults
      }
    },
    /**
     * Saves node positions to local storage.
     */
    savePositionsToStorage() {
      localStorage.setItem(SAVE_KEY_NAME, JSON.stringify(this.nodePositions));
    },
    setCurrentGraphId(currentGraphId: string) {
      this.currentGraphId = currentGraphId;
      if (!this.nodePositions[currentGraphId]) {
        this.nodePositions[currentGraphId] = { TB: [], LR: [] };
      }
    },
  },
});