//
//  KMPDFViewAnnotationOnceModeStore.swift
//  PDF Office
//
//  Created by tangchao on 2023/4/20.
//

import Cocoa

class KMPDFViewAnnotationOnceModeStore: KMMemorandumPattern<CPDFListView> {
    internal var annotationType = CAnnotationType.unkown
    internal var toolMode = CToolMode.textToolMode
    
    override func store(t: CPDFListView) {
        self.toolMode = t.toolMode
        self.annotationType = t.annotationType
    }
    
    override func restore(t: CPDFListView) {
        t.toolMode = self.toolMode
        t.annotationType = self.annotationType
    }
}

class KMPDFViewRemoveAllAnnotationsStore: KMMemorandumPattern<CPDFListView> {
    internal var annotations: [CPDFAnnotation] = []
    internal var undoManager = UndoManager()
    
    override func store(t: CPDFListView) {
        // 清空
        self.annotations.removeAll()
        
        // 存储所有注释
        for pageIdx in 0 ..< t.document.pageCount {
            let page = t.document.page(at: pageIdx)
            if let annotations = page?.annotations {
                self.annotations.append(contentsOf: annotations)
            }
                
            page?.removeAllAnnotations()
        }
        // 刷新UI
        t.setNeedsDisplayForVisiblePages()
        // undo
        t.undoManager?.registerUndo(withTarget: self) { target in
            target.restore(t: t)
        }
    }
    
    override func restore(t: CPDFListView) {
        // 恢复所有注释
        for anno in self.annotations {
            if (anno.page.annotations.contains(anno)) {
                continue
            }
            anno.page.addAnnotation(anno)
        }
        // 刷新UI
        t.setNeedsDisplayForVisiblePages()
        // 清空
        self.annotations.removeAll()
        // undo
        t.undoManager?.registerUndo(withTarget: self) { target in
            target.store(t: t)
        }
    }
}