export class ContentEditHistoryManager {
  constructor(options) {
    this.messageHandler = options.messageHandler
    this.eventBus = options.eventBus
    this.pdfViewer = options.pdfViewer

    this.undoList = []
    this.redoList = []

    this.eventBus._on('toolModeChanged', this.handleToolMode.bind(this))
  }

  async canRedo(data) {
    if (!data) return this.redoList.length > 0
    
    if (!data.editPagePtr) return false
    const res = await this.messageHandler.sendWithPromise('CanRedo', data.editPagePtr)
    return !!res
  }

  async canUndo(data) {
    if (!data) return this.undoList.length > 0
    
    if (!data.editPagePtr) return false
    const res = await this.messageHandler.sendWithPromise('CanUndo', data.editPagePtr)
    return !!res
  }

  async redo() {
    const lastRedo = this.redoList.pop()
    if (!lastRedo) {
      console.warn('No actions to redo')
      return false
    }
    const res = await this.messageHandler.sendWithPromise('Redo', lastRedo.editPagePtr)

    this.undoList.push(lastRedo)
    this.updateView(lastRedo.pageIndex, res)

    this.eventBus.dispatch('undoRedoStatusChanged')
  }

  async undo() {
    const lastUndo = this.undoList.pop()
    if (!lastUndo) {
      console.warn('No actions to undo')
      return false
    }
    const res = await this.messageHandler.sendWithPromise('Undo', lastUndo.editPagePtr)
    const canRedo = await this.canRedo(lastUndo)

    canRedo && this.redoList.push(lastUndo)
    this.updateView(lastUndo.pageIndex, res)

    this.eventBus.dispatch('undoRedoStatusChanged')
  }

  async updateView(pageIndex, res) {
    await this.pdfViewer._pages[pageIndex].contentContainer.updateFrameEditor(res)

    this.eventBus.dispatch('changeOperateList', {
      undoListLength: this.undoList.length,
      redoListLength: this.redoList.length
    })
  }

  handleToolMode(mode) {
    if (mode !== 'editor' && (this.undoList.length || this.redoList.length)) {
      this.undoList.length = 0
      this.redoList.length = 0
    }
  }
}
