//
//  PDFImageCache.swift
//  PrinterDemo
//
//  Created by ios on 2021/12/18.
//  Copyright © 2021 Printer. All rights reserved.
//

import UIKit

class PDFImageCache: NSObject {

    var maxCacheCount = 5
    var caches = [Int: PDFDataProvider]()
    var indexQueue = [Int]()
    
    func append(generator: PDFDataProvider, index: Int) -> Void {
        caches[index] = generator
        if let i = indexQueue.firstIndex(of: index) {
            indexQueue.remove(at: i)
        }
        indexQueue.append(index)
        
        if indexQueue.count > maxCacheCount {
            let i = indexQueue.remove(at: 0)
            let generator = caches.removeValue(forKey: i)
            generator?.clearPreviewImage()
        }
    } 
    
    func cachedImage(at index: Int) -> PDFDataProvider? {
        return caches[index]
    }
    
    func clear() -> Void {
        for index in indexQueue {
            caches[index]?.clearPreviewImage()
        }
        caches.removeAll()
        indexQueue.removeAll()
    }
}
