/**
 * Whiteboard History Manager - 白板历史记录管理器
 *
 * 基于 MindMap HistoryManager 模式，适配白板数据类型
 */

import type { SerializedBoard } from './types'

/** 历史记录项 */
interface HistoryItem {
  data: SerializedBoard
  action?: string
  timestamp: number
}

/** 历史管理器配置 */
interface BoardHistoryOptions {
  maxHistory?: number
}

export class BoardHistoryManager {
  private stack: HistoryItem[] = []
  private pointer: number = -1
  private maxHistory: number

  constructor(options: BoardHistoryOptions = {}) {
    this.maxHistory = options.maxHistory ?? 50
  }

  get canUndo(): boolean {
    return this.pointer > 0
  }

  get canRedo(): boolean {
    return this.pointer < this.stack.length - 1
  }

  get length(): number {
    return this.stack.length
  }

  push(data: SerializedBoard, action?: string): void {
    const snapshot: HistoryItem = {
      data: JSON.parse(JSON.stringify(data)),
      action,
      timestamp: Date.now(),
    }

    if (this.pointer < this.stack.length - 1) {
      this.stack = this.stack.slice(0, this.pointer + 1)
    }

    this.stack.push(snapshot)
    this.pointer = this.stack.length - 1

    if (this.stack.length > this.maxHistory) {
      this.stack.shift()
      this.pointer--
    }
  }

  undo(): HistoryItem | null {
    if (!this.canUndo) return null
    this.pointer--
    return this.stack[this.pointer]
  }

  redo(): HistoryItem | null {
    if (!this.canRedo) return null
    this.pointer++
    return this.stack[this.pointer]
  }

  getCurrent(): HistoryItem | null {
    if (this.pointer < 0 || this.pointer >= this.stack.length) return null
    return this.stack[this.pointer]
  }

  clear(): void {
    this.stack = []
    this.pointer = -1
  }

  init(data: SerializedBoard): void {
    this.clear()
    this.stack.push({
      data: JSON.parse(JSON.stringify(data)),
      action: 'Initial',
      timestamp: Date.now(),
    })
    this.pointer = 0
  }

  replaceCurrent(data: SerializedBoard, action?: string): void {
    if (this.pointer < 0) {
      this.push(data, action)
      return
    }
    this.stack[this.pointer] = {
      data: JSON.parse(JSON.stringify(data)),
      action,
      timestamp: Date.now(),
    }
  }
}

export default BoardHistoryManager
