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

import Foundation
import ComPDFKit_Conversion
import PDFKit

let KMComPDFKit_Conversion_FreeKey = "0GlqazsfP4IwQoWL/6baqg+CN7l67d9FF0N3U4bBSLhmvR60yAnkkBesqA8agcAaswc5ugjeuEvGnUqi7SLvz6k8f7LqcbDiVIQLTv57527J0AoKYSECIVvbiY9V1ITRv0GI+05iQtIRD9CPDVIoSf/TPiylxglXhnl6PeFazoA=";
let KMComPDFKit_Conversion_FreeSecret = "mG0c3O3Mzeu5dkZJW3gpqqFRGIktEUTr3N7MWERzNh/7rDlDXAYp6ebnHnHEdcFleiP4OkM17dhQ9pWvnVPbJOIDC/XIeZ7j/POUbhtIPbOZ3pnCWorSKPeQWqupmvSjMv7C2jvq4o0q6sQtN3jR4897KG6mIUGJSRuOsvjYroXP4neJlIQii5tjFEKC59L5S32wgJX2ceb3xBQSCnO9vtnsa41fJuMqWbPW2c3qJUemdtKP7E4eFYSl6tjgcetK";

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 {
        self.srcPath = inSrcPath
        self.desPath = inDesPath
        
        if !FileManager.default.fileExists(atPath: srcPath) {
            return false
        }
        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!
            }
        }
         
        accessSemaphore?.wait()
        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: ["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)
        
        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()
    }
    
}
