//
//  FileConverter.swift
//  KdanAuto
//
//  Created by 朱东勇 on 2022/12/21.
//

import Foundation
import ComPDFKit_Conversion
import PDFKit

let KMComPDFKit_Conversion_FreeKey = "hw5vIMzKU2Im6cPijLjG45VAHy01ikUF5/GdAMdzCV8n2QTKNN0d8kG8crVbGYjIMsvVP+A9gx5g+W8qEi4ho0YTkGDratHOrX68W7khEBHAv7OEyRxIhlhBmdEQD+21lsRpIEW5zucUAF231lo3ZZiiT2s9CualDQJdAo1G0DI=";
let KMComPDFKit_Conversion_FreeSecret = "mG0c3O3Mzeu5dkZJW3gpqh188cTuhYlGRPrbR/gfX4p9ms/F1zY6gZ1RBu8mNJH8zLwqe9EJswNmwV09TNi2IiIDeG7Ulx+U4pbeFB3/eYl2J6LePb3Kl54OsKlYiaf3Mv7C2jvq4o0q6sQtN3jR4897KG6mIUGJSRuOsvjYroVgMwna6EUx0K0SBmBGoFYDYkwcNWVMyYvggPV2rTFvfawopGIC034QzjthmhwwX90=";

let KMPDFConvertOptionsKeyImageDPI = "KMPDFConvertOptionsKeyImageDPI"
let KMPDFConvertOptionsKeyImageWithAnnotation = "KMPDFConvertOptionsKeyImageWithAnnotation"


let kDefaultPassword = "666666"

class FileConverter : NSObject, CPDFConverterDelegate, CPDFConverterFPDelegate {
    
    var pdfConverter:CPDFConverter?
    var fpConverter:CPDFConverterFP?
    var options:CPDFConvertOptions?
    
    var srcPath:String = ""
    var desPath:String = ""
    var pages:[Int] = []
    var pathExtension = ""
    var convertQueue = DispatchQueue.main
    
    var semaphore:DispatchSemaphore? = DispatchSemaphore.init(value: 0)
    var accessSemaphore:DispatchSemaphore? = DispatchSemaphore.init(value: 1)
    var didSuccess:Bool = false
    
    static var instance = FileConverter()
    class func shared() -> FileConverter {
        return instance
    }
    
    func converter(_ inSrcPath: String, inDesPath: String) -> Bool {
        if !FileManager.default.fileExists(atPath: inSrcPath) {
            return false
        }
        
        accessSemaphore?.wait()
        
        self.srcPath = inSrcPath
        self.desPath = inDesPath
        
        if FileManager.default.fileExists(atPath: desPath) {
            try! FileManager.default.removeItem(atPath: desPath)
        }
        let attributy = try! FileManager.default.attributesOfItem(atPath: srcPath)
        let fileType = attributy[FileAttributeKey.type] as! FileAttributeType
        if NSString(string: FileAttributeType.typeSymbolicLink.rawValue).isEqual(to: fileType.rawValue) {
            let symbolicLink = try? FileManager.default.destinationOfSymbolicLink(atPath: self.srcPath)
            if nil != symbolicLink {
                self.srcPath = symbolicLink!
            }
        }
         
        if FileManager.default.fileExists(atPath: self.desPath) {
            try! FileManager.default.removeItem(atPath: self.desPath)
        }
        
        self.pathExtension = NSString(string: self.desPath).pathExtension
//        let outputPath = NSString(string: self.desPath).deletingPathExtension
//        let output = self.desPath
        self.convertQueue.async {
            let url = URL.init(fileURLWithPath: self.srcPath, isDirectory: false)
            let document = PDFDocument(url: url)
            if document == nil {
                self.accessSemaphore?.signal()
                return
            }
            let pageCount = document!.pageCount
            
            self.pages = []
            for i in 1...pageCount {
                self.pages.append(i)
            }
            
            if NSArray(array: ["jpg", "JPG", "png", "PNG"]).contains(self.pathExtension) {
                let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
                self.pdfConverter = CPDFConverterImg.init(url: url, password: nil)
                self.pdfConverter?.delegate = self
                self.options = CPDFConvertImgOptions()
                self.pdfConverter?.convert(toFilePath: cachePath, pageIndexs: self.pages, options: self.options)
            }else {
                
                //            if NSArray(array: ["ppt", "PPT", "PPTX", "pptx"]).contains(pathExtension) {
                //                self.pdfConverter = CPDFConverterPPT.init(url: url, password: kDefaultPassword)
                //                self.pdfConverter?.delegate = self
                //                self.options = CPDFConvertPPTOptions()
                //                self.pdfConverter?.convert(toFilePath: outputPath,
                //                                           pageIndexs: [], options: nil)
                //            }else
                //            if NSArray(array: ["doc", "DOC", "docx", "DOCX"]).contains(pathExtension) {
                //                self.pdfConverter = CPDFConverterWord.init(url: url, password: nil)
                //                self.pdfConverter?.delegate = self
                //                self.options = CPDFConvertWordOptions()
                //                self.pdfConverter?.convert(toFilePath: self.self.desPath,
                //                                           pageIndexs: pagesArray, options: nil)
                //            }else
                //            if NSArray(array: ["xls", "XLS", "xlsx", "XLSX"]).contains(pathExtension) {
                //                self.pdfConverter = CPDFConverterTable.init(url: url, password: nil)
                //                self.pdfConverter?.delegate = self
                //                self.options = CPDFConvertTableOptions()
                //                self.pdfConverter?.convert(toFilePath: self.self.desPath,
                //                                           pageIndexs: pagesArray, options: nil)
                //            }else if NSArray(array: ["csv", "CSV"]).contains(pathExtension) {
                //                self.pdfConverter = CPDFConverterCsv.init(url: url, password: nil)
                //                self.pdfConverter?.delegate = self
                //                self.options = CPDFConvertCsvOptions()
                //                self.pdfConverter?.convert(toFilePath: self.self.desPath,
                //                                           pageIndexs: pagesArray, options: nil)
                //            }else {
                if self.fpConverter == nil {
                    self.fpConverter = CPDFConverterFP.init()
                    self.fpConverter?.setDelegate(self)
                }else {
                    self.fpConverter?.stopConvertsionIfNeed()
                }
                
                
                let needMerge = NSArray(array: ["csv", "CSV"]).contains(self.pathExtension)
                //                let allInOneSheetKey = String(CPDFConvertOptionsKey.allInOneSheet)
                
                //            Task.init {
                self.fpConverter?.convertPDF(atPath: self.srcPath,
                                             pdfPassword: nil,
                                             pdfPageIndexs: self.pages,
                                             destDocType: self.pathExtension,
                                             destDocPath: self.desPath,
                                             moreOptions: [
                                                "KMPDFConvertOptionsKeyImageDPI" : "72",
                                                "CPDFConvertOptionsKeyAllInOneSheet":NSNumber(booleanLiteral: needMerge)
                                             ])
                //            }
                //            }
            }
        }
        
        semaphore?.wait()
        accessSemaphore?.signal()
        
        return didSuccess
    }
    
    /// CPDFConverterDelegate
    func converter(_ converter: CPDFConverter!, didStartConvert error: Error!) {
        
    }
    
    func converter(_ converter: CPDFConverter!, didEndConvert error: Error!) {
        didSuccess = nil == error
        
        sleep(2)
        
        let cachePath = NSString(string: self.desPath).deletingPathExtension+".zip"
//        try? FileManager.default.createDirectory(atPath: self.desPath, withIntermediateDirectories: true)
        
        let zip = ZipArchive.init()
        
        zip.unzipOpenFile(cachePath)
        zip.unzipFile(to: self.desPath, overWrite: true)
        
        try? FileManager.default.removeItem(atPath: cachePath)
        
        sleep(1)
        
        if self.pdfConverter?.isConverting == true {
            self.pdfConverter?.cancel()
        }
        self.pdfConverter?.delegate = nil
        self.pdfConverter = nil
        semaphore?.signal()
    }
    
    func converter(_ converter: CPDFConverter!, pageIndex index: UInt, pageCount count: UInt) {
        
    }
    
    /// CPDFConverterFPDelegate
    func fppdfConverter(_ converter: Any!, didEndConversion error: Error!) {
        didSuccess = nil == error
        self.fpConverter?.stopConvertsionIfNeed()
        
        sleep(2)
        
//        self.fpConverter?.stopConvertsionIfNeed()
//        self.fpConverter?.setDelegate(nil)
//        self.fpConverter = nil
//        
        semaphore?.signal()
    }
    
}
