//
//  KMSecurityView.swift
//  PDF Reader Pro
//
//  Created by lizhe on 2023/11/13.
//

import Cocoa
import KMComponentLibrary

typealias KMSecurityViewBatchAction = (_ view: KMSecurityView, _ files: [KMFileAttribute]) -> Void
typealias KMSecurityViewCancelAction = (_ view: KMSecurityView) -> Void
typealias KMSecurityViewDoneAction = (_ view: KMSecurityView, _ model: KMSecureEncryptModel, _ files: [KMFileAttribute]) -> Void

class KMSecurityView: BaseXibView {
    
    @IBOutlet weak var box1: NSBox!
    
    @IBOutlet var batchButton: ComponentButton!
    @IBOutlet var cancelButton: ComponentButton!
    @IBOutlet var doneButton: ComponentButton!
    
    @IBOutlet var batchWidthConst: NSLayoutConstraint!
    @IBOutlet var cancelWidthConst: NSLayoutConstraint!
    @IBOutlet var doneWidthConst: NSLayoutConstraint!
    
    @IBOutlet weak var securityContentView: KMSecurityContentView!
    
    var batchAction: KMSecurityViewBatchAction?
    var cancelAction: KMSecurityViewCancelAction?
    var doneAction: KMSecurityViewDoneAction?
    
    var openPasswordString: String?
    var ownerPasswordString: String?
    
    var files: [KMFileAttribute] = []
    
    private var model: KMSecureEncryptModel = KMSecureEncryptModel()
    var canEncrypt: Bool = false
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        // Drawing code here.
    }
    
    override func setup() {
        self.securityContentView.model = self.model
        
        updateLanguage()
    }
    
    func updateLanguage() {
        box1.fillColor = NSColor.clear
                
        batchButton.properties = ComponentButtonProperty(type: .default_tertiary,
                                                         size: .s,
                                                         state: .normal,
                                                         onlyIcon: false,
                                                         buttonText: KMLocalizedString("Batch"))
        batchButton.setTarget(self, action: #selector(batchButtonAction(_:)))
        batchWidthConst.constant = batchButton.properties.propertyInfo.viewWidth
        
        cancelButton.properties = ComponentButtonProperty(type: .default_tertiary,
                                                          size: .s,
                                                          state: .normal,
                                                          onlyIcon: false,
                                                          buttonText: KMLocalizedString("Cancel"))
        cancelButton.setTarget(self, action: #selector(cancelButtonAction(_:)))
        cancelWidthConst.constant = cancelButton.properties.propertyInfo.viewWidth
        
        doneButton.properties = ComponentButtonProperty(type: .primary,
                                                        size: .s,
                                                        state: .normal,
                                                        onlyIcon: false,
                                                        buttonText: KMLocalizedString("Encrypt"))
        doneButton.setTarget(self, action: #selector(doneButtonAction(_:)))
        doneWidthConst.constant = doneButton.properties.propertyInfo.viewWidth
        
    }
    
    func reloadData() {
        
        self.updateEncryptButtonEnabledState()
    }
    
    override func mouseDown(with event: NSEvent) {
        super.mouseDown(with: event)
        
        self.window?.makeFirstResponder(nil)
    }
}

extension KMSecurityView {
    func updateEncryptButtonEnabledState() {
        var enabled = false
        if model.openPasswordOn {
            if !model.openPassword.isEmpty {
                enabled = true
            }
        }
        
        if enabled {
            if model.ownerPasswordOn {
                if model.ownerPassword.count == 0 || (model.printAllowed && model.editAllowed) {
                    enabled = false
                }
            }
        } else {
            if model.ownerPasswordOn {
                if !model.ownerPassword.isEmpty && (!model.printAllowed || !model.editAllowed) {
                    enabled = true
                }
            }
        }
        
        self.canEncrypt = enabled
        if enabled {
            doneButton.properties.isDisabled = false
        } else {
            doneButton.properties.isDisabled = true
        }
        doneButton.reloadData()
    }
}

extension KMSecurityView {
    @objc func batchButtonAction(_ sender: Any) {
        if !IAPProductsManager.default().isAvailableAllFunction(){
            KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
            return
        }
        guard let callBack = batchAction else { return }
        
        callBack(self, files)
    }
    
    @objc func cancelButtonAction(_ sender: Any) {
        guard let callBack = cancelAction else { return }
        
        callBack(self)
    }
    
    @objc func doneButtonAction(_ sender: Any) {
        self.securityContentView.updatePasswordState()
        
        if model.ownerPassword == model.openPassword {
            let alert = NSAlert()
            alert.alertStyle = .critical
            alert.messageText = NSLocalizedString("The Open and Owner passwords cannot be the same. Please change either the Open or the Owner Password.", comment: "")
            alert.runModal()
            return
        }
        
        guard let callBack = doneAction else { return }
        
        callBack(self, model, files)
    }
}