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

import UIKit
import SwifterBaseKit
import PrinterSDK

class PDFDataProvider {
    
    init(with processable: PDFDataProcessor,
         interestRect: CGRect = CGRect.init(x: 0, y: 0, width: 1, height: 1),
         outputSize: CGSize
    ) {
        self.processable = processable
        let h = outputSize.width * processable.height / processable.width
        self.outputSize = CGSize(width: outputSize.width, height: h)
        self.interestRect = interestRect
    }
    
    private var processable: PDFDataProcessor
    private var outputSize: CGSize
    private var interestRect: CGRect
    
    var previewImage : UIImage!
    
    func clearPreviewImage() -> Void {
        autoreleasepool {
            self.previewImage = nil
        }
    }
    
    func getOriginImage() -> Void {
        self.previewImage = self.getAllImages()
    }
    
    private func getAllImages() -> UIImage {
        autoreleasepool {
            self.getAspectFitImage()
        }
    }
    
    private func getAspectFitImage() -> UIImage {
        let destSize = CGSize(width: CGFloat(ceil(outputSize.width)), height: CGFloat(ceil(outputSize.height)))
        let result: UIImage
        
        UIGraphicsBeginImageContextWithOptions(destSize, false, 1.0)
        let ctx = UIGraphicsGetCurrentContext()!
        ctx.setFillColor(UIColor.white.cgColor)
        ctx.fill(CGRect(origin: .zero, size: destSize))
        ctx.saveGState()
        ctx.interpolationQuality = .high
        ctx.setRenderingIntent(.absoluteColorimetric)
        
        let scale = min(destSize.width/processable.width, destSize.height/processable.height)
        ctx.scaleBy(x: scale, y: scale)
        let drawSize = destSize / scale
        ctx.translateBy(x: (drawSize.width - processable.width)/2, y: (drawSize.height - processable.height)/2)
        processable.draw(ctx: ctx)
        ctx.restoreGState()
        
        result = UIGraphicsGetImageFromCurrentImageContext()!
        
//        let actualW = tempSize.width - (drawSize.width - processable.width) * scale
//        let actualH = tempSize.height - (drawSize.height - processable.height) * scale
        
        UIGraphicsEndImageContext()
        return result
    }
}


public func / (size: CGSize, divided: CGFloat) -> CGSize {
    
    return CGSize.init(width: size.width/divided, height: size.height/divided)
}



