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

import UIKit
import PDFKit

public extension CGSize {
    
    var ratio: CGFloat {
        
        return width/height
    }
}

struct A4 {
    
    static func getSize() -> CGSize {
        let paperWidth = kUserDefaults.integer(forKey: PDPrintDots)
        let paperHeight = 842 * paperWidth / 595
        return CGSize(width: paperWidth, height: paperHeight)
    }
}


protocol PDFConvertible {
    func generate(_ pdfSize: CGSize) -> [PDFDataProcessor]
}

extension Array: PDFConvertible where Element: UIImage {
    
    func generate(_ pdfSize: CGSize) -> [PDFDataProcessor] {
        return self
    }
}

extension URL: PDFConvertible {

    func generate(_ pdfSize: CGSize) -> [PDFDataProcessor] {
        var processables = [PDFDataProcessor]()
        if #available(iOS 11, *) {
            if let document = PDFDocument.init(url: self) {
                for i in 0..<document.pageCount {
                    processables.append(document.page(at: i)!)
                }
            }
        }else {
            if let document = CGPDFDocument.init(self as CFURL) {
                for i in 1...document.numberOfPages {
                    processables.append(document.page(at: i)!)
                }
            }
        }
        
       // 自动旋转PDF
        for i in 0..<processables.count {
            var needRotate = false
            let processable = processables[i]
            let width = processable.width
            let height = processable.height
            if width != height  {
                if (width/height - 1)*(pdfSize.ratio - 1) < 0 {
                    needRotate = true
                }
            }
            if needRotate {
                processables[i] = processable.baw_rotate90(clockwise: true)
            }
        }
        return processables
    }
}


