//
//  KMCompressWIndowControllerNew.swift
//  PDF Reader Pro
//
//  Created by lizhe on 2023/11/8.
//

import Cocoa

typealias KMCompressWIndowControllerNewBatchAction = (_ view: KMCompressWIndowControllerNew, _ filePaths: [URL]) -> Void
typealias KMCompressWIndowControllerNewItemClick = () -> Void
typealias KMCompressWIndowControllerNewResultCallback = (_ result: Bool,_ openDocuemt: Bool, _ fileURL: URL, _ error: String)->()

class KMCompressWIndowControllerNew: KMBaseWindowController {
    @IBOutlet weak var compressView: KMCompressView!
    
    var resultCallback: KMCompressWIndowControllerNewResultCallback!
    var itemClick: KMCompressWIndowControllerNewItemClick?
    var batchAction: KMCompressWIndowControllerNewBatchAction?
    
    var documentURL: URL! {
        didSet{
            if self.password.count != 0 {
                self.compressView.documentURL = self.documentURL
            } else {
                KMBaseWindowController.checkPassword(url: documentURL, type: .owner) { [unowned self] success, paasswordString in
                    if success {
                        self.password = paasswordString
                        self.compressView.documentURL = self.documentURL
                    } else {
                        guard let callBack = self.itemClick else { return }
                        
                        callBack()
                    }
                }
            }
        }
    }
    
    var password: String = "" {
        didSet {
            self.compressView.password = password
        }
    }
    private var datas: [String] = []
    
    var limit = true
    var oriDocumentUrl: URL?
    
    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        
        self.compressView.cancelAction = { [weak self] view in
//            self.closeWindow()
            
            guard let callBack = self?.itemClick else { return }
            
            callBack()
        }
        
        self.compressView.batchAction = { [unowned self] view in
            print("Batch 按钮点击")
            if !IAPProductsManager.default().isAvailableAllFunction(){
                KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
                return
            }
            guard let callBack = batchAction else { return }
            
            callBack(self, [documentURL])
        }
        
        self.compressView.compressAction = { [weak self] view, value in
            self?.compressButtonAction(value: value)
        }
    }
    
    private func compressButtonAction(value: Int, limit: Bool = false) {
        DispatchQueue.main.async {
            NSPanel.savePanel(self.window!, true) { panel in
                var url: URL = self.documentURL
                if (self.oriDocumentUrl != nil) {
                    url = self.oriDocumentUrl!
                }
                panel.nameFieldStringValue = ""+url.deletingPathExtension().lastPathComponent+"_Compressed"
                panel.allowedFileTypes = ["pdf"]
            } completion: { response, url, isOpen in
                if (response == .cancel) {
                    return
                }
                
                self.beginLoading()
                DispatchQueue.global().async {
                    let docuemt = CPDFDocument.init(url: self.documentURL)
                    if (docuemt?.isLocked)! && self.password != nil {
                        docuemt?.unlock(withPassword: self.password)
                    }
                    
                    let option = value
                    
                    var result = false
                    if (limit) {
                        if let _document = docuemt, let _ = KMTools.saveWatermarkDocumentForCompress(document: _document, to: url!, imageQuality: option) {
                            result = true
                        }
                    } else {
                        if let data = docuemt?.writeOptimize(to: url, withOptions: [.imageQualityOption : option]) {
                            result = data
                        }
                    }
                    
                    if (result) {
                        self._clearData()
                    }
                    
                    DispatchQueue.main.async {
                        self.endLoading()
                        guard let callback = self.resultCallback else {
                            if (result) {
                                if isOpen { /// 开启文档
                                    NSDocumentController.shared.km_safe_openDocument(withContentsOf: url!, display: true) { _, _, _ in
                                        
                                    }
                                } else {
                                    NSWorkspace.shared.activateFileViewerSelecting([url!])
                                }
                            }
                            return
                        }
                        
                        callback(result, isOpen, url!, "")
                    }
                }
            }
        }
    }
    
    private func _clearData() {
        if let _ = self.oriDocumentUrl {
            if let data = self.documentURL?.path, FileManager.default.fileExists(atPath: data) {
                try?FileManager.default.removeItem(atPath: data)
            }
        }
    }
    
    func closeWindow() {
        self.close()
    }
}

extension KMCompressWIndowControllerNew: KMLoadingProtocol {
    func beginLoading() {
        self.window?.contentView?.beginLoading()
    }
    
    func endLoading() {
        self.window?.contentView?.endLoading()
    }
}