//
//  KMBaseWindowController.swift
//  PDF Reader Pro
//
//  Created by tangchao on 2023/5/11.
//

import Cocoa

class KMBaseWindowController: NSWindowController {
    
    var cancelAction: KMCommonBlock?
    var pdfDocument: CPDFDocument?
    var isBates: Bool = false
    var isBatch: Bool = false  //是否批量模块进入
    deinit {
        Swift.debugPrint(self.className + "已释放")
        
        self.removeNotification()
    }
    
    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.initSubViews()
        self.initDefaultValue()
        self.initNotification()
    }
    
    func initSubViews() {}
    func initDefaultValue() {
        self.window?.appearance = NSApp.appearance
    }
    
    func initNotification() {
        DistributedNotificationCenter.default().addObserver(self, selector: #selector(_themeChanged), name: NSApplication.interfaceThemeChangedNotification, object: nil)
    }
    
    func removeNotification() {
        DistributedNotificationCenter.default().removeObserver(self)
    }
    
    func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
        
    }
}

// MARK: - Private Methods

extension KMBaseWindowController {
    @objc private func _themeChanged(_ sender: Notification) {
        let isDarkModel = KMAdvertisementConfig.isDarkModel()
        if isDarkModel {
            self.window?.appearance = .init(named: .darkAqua)
        } else {
            self.window?.appearance = .init(named: .aqua)
        }
        
        Task { @MainActor in
            self.interfaceThemeDidChanged(self.window?.appearance?.name ?? .aqua)
        }
    }
}

extension NSWindowController {
    func kCheckPassword(url: URL, type: KMPasswordInputWindowType, password: String = "", completion: @escaping ((_ success: Bool, _ resultPassword: String) -> Void)) {
        // 判断路径 + document
        guard let document = CPDFDocument.init(url: url) else {
            return completion(false, "")
        }

        // 判断是否为加密文档
        if document.isLocked == false {
            if type == .open {
                completion(true, "")
                return
            }
        }
        
        if document.isLocked == false && (document.allowsCopying && document.allowsPrinting) {
            completion(true, "")
            return
        }
        
        // 加密文件,尝试解锁
        if password.isEmpty == false {
            let preStatus = document.permissionsStatus
            document.unlock(withPassword: password)
            if document.permissionsStatus.rawValue > preStatus.rawValue { // 解密成功
                completion(true, password)
                return
            }
        }
        
        // 弹密码弹窗
        Task { @MainActor in
            KMPasswordInputWindow.openWindow(window: self.window!, type: type, url: url) { result , password in
                if (result == .cancel) {
                    completion(false, "")
                    return
                } else {
                    completion(true, password ?? "")
                }
            }
        }
    }
}

extension KMBaseWindowController {
    static func checkPassword(url: URL, type: KMPasswordInputWindowType, password: String = "", completion: @escaping ((_ success: Bool, _ resultPassword: String) -> Void)) {
        // 判断路径 + document
        guard let document = CPDFDocument.init(url: url) else {
            return completion(false, "")
        }

        // 判断是否为加密文档
        if document.isLocked == false {
            if type == .open {
                completion(true, "")
                return
            }
        }
        
        if document.isLocked == false && (document.allowsCopying && document.allowsPrinting) {
            completion(true, "")
            return
        }
        
        // 加密文件,尝试解锁
        if password.isEmpty == false {
            let preStatus = document.permissionsStatus
            document.unlock(withPassword: password)
            if document.permissionsStatus.rawValue > preStatus.rawValue { // 解密成功
                completion(true, password)
                return
            }
        }
        
        // 弹密码弹窗
        Task { @MainActor in
            KMPasswordInputWindow.openWindow(window: NSWindow.currentWindow(), type: type, url: url) { result , password in
                if (result == .cancel) {
                    completion(false, "")
                    return
                } else {
                    completion(true, password ?? "")
                }
            }
        }
    }
}