//
//  DSignatureFromFileViewController.swift
//  PDF Reader Pro Edition
//
//  Created by Niehaoyu on 2023/9/28.
//

import Cocoa

class DSignatureFromFileViewController: NSViewController, NSTextFieldDelegate {

    @IBOutlet weak var titleLabel: NSTextField!
    @IBOutlet weak var subTitleLabel: NSTextField!
    
    @IBOutlet weak var filesLabel: NSTextField!
    @IBOutlet weak var filesTextFiled: NSTextField!
    @IBOutlet weak var passwordLabel: NSTextField!
    @IBOutlet weak var passwordTextFiled: NSSecureTextField!
    @IBOutlet weak var browseButton: NSButton!
    @IBOutlet weak var errorLabel: NSTextField!
    
    @IBOutlet weak var promptBox: NSBox!
    @IBOutlet var promptTextView: NSTextView!
    
    @IBOutlet weak var continueButton: NSButton!
    @IBOutlet weak var previousStepButton: NSButton!
    @IBOutlet weak var creatButton: NSButton!
    

    var actionBlock: ((_ fromFileVC:DSignatureFromFileViewController, _ action:DSignatureActionType, _ cer:NSDictionary)->Void)?
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        self.filesTextFiled.delegate = self
        self.passwordTextFiled.delegate = self
        
        self.localizedLanguage()
        
        self.titleLabel.textColor = NSColor.labelColor
        self.subTitleLabel.textColor = NSColor.labelColor
        self.filesLabel.textColor = NSColor.labelColor
        self.passwordLabel.textColor = NSColor.labelColor
        
        self.filesTextFiled.textColor = NSColor.labelColor
        self.passwordTextFiled.textColor = NSColor.labelColor
        
        self.promptTextView.textColor = NSColor.labelColor
        
        self.filesTextFiled.wantsLayer = true
        self.passwordTextFiled.wantsLayer = true
        
        self.filesTextFiled.layer?.borderWidth = 1
        self.passwordTextFiled.layer?.borderWidth = 1
        
        self.filesTextFiled.layer?.cornerRadius = 5
        self.passwordTextFiled.layer?.cornerRadius = 5
        
        self.passwordTextFiled.updateState(false)
        self.errorLabel.isHidden = true
        
        self.filesTextFiled.updateState(false)
        
    }
    
    func localizedLanguage() {
        self.titleLabel.stringValue = NSLocalizedString("Find a Digital ID File", comment: "")
        self.subTitleLabel.stringValue = NSLocalizedString("Browse for a digital ID file. Digital ID files are password protected. You cannot access the digital ID if you don't know its password.", comment: "");
        self.filesLabel.stringValue = NSLocalizedString("File",comment: "");
        self.passwordLabel.stringValue = NSLocalizedString("Password",comment: "");
        self.filesTextFiled.placeholderString  = NSLocalizedString("Select a file", comment: "");
        self.promptTextView.string = String(format: "%@\n\n%@",NSLocalizedString("Digital ID files generally have a P12 extension and contain the public key file (Certificate) and the associated private key file.", comment: ""),NSLocalizedString("To sign with a digital ID available as a file, follow the prompts to browse and select the file and type the password protecting the private key.",comment: ""))
        self.errorLabel.stringValue = NSLocalizedString("Password is incorrect. Please re-enter the password.", comment: "")
        
        self.browseButton.title = String(format:"%@",NSLocalizedString("Browse", comment: ""))
        self.previousStepButton.title = NSLocalizedString("Previous Step",comment: "");
        self.creatButton.title = NSLocalizedString("Configure New Digital ID", comment: "");
        self.continueButton.title = NSLocalizedString("Continue", comment: "");
    }
    
    func updateTextFiedState() {
        if (self.filesTextFiled.stringValue.isEmpty == false) {
            self.filesTextFiled.updateState(false)
        } else {
            self.filesTextFiled.updateState(true)
        }
        
        if self.filesTextFiled.stringValue.isEmpty == false {
            self.continueButton.isEnabled = true
        } else {
            self.continueButton.isEnabled = false
        }
    }
    
    //MARK: IBAction
    
    @IBAction func closeAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .cancel, NSDictionary())
    }
    
    @IBAction func fileBrowse(_ sender: Any) {
        let openPanel = NSOpenPanel()
        openPanel.allowedFileTypes = ["p12","pfx"]
        openPanel.beginSheetModal(for: self.view.window!) { result in
            if result == .OK {
                let fileURL = openPanel.urls.first
                self.filesTextFiled.stringValue = fileURL!.path
            }
            self.updateTextFiedState()
        }
    }
    
    @IBAction func configNewAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .createNewDsign, NSDictionary())
    }
    
    @IBAction func previousAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .previousStep, NSDictionary())
    }
    
    @IBAction func continueAction(_ sender: Any) {
        let filePath = self.filesTextFiled.stringValue
        if FileManager.default.fileExists(atPath: filePath) {
            let identity = KMDSignatureManager.privateKeyUsingSecItemImport(fromP12File: filePath, password: self.passwordTextFiled.stringValue)
            if identity != nil {
                let dic = NSMutableDictionary.init()
                dic.setValue(filePath, forKey: SAVEFILEPATH_KEY)
                dic.setValue(self.passwordTextFiled.stringValue, forKey: PASSWORD_KEY)
                
                let moveSuc = KMDSignatureManager.default().moveP12DigitalFile(withFilePath: filePath, password: self.passwordTextFiled.stringValue)
                if moveSuc {
                    guard let callBack = self.actionBlock else {
                        return
                    }
                    callBack(self, .confirm, dic)
                } else {
                    let alert = NSAlert.init()
                    alert.messageText = NSLocalizedString("Failed to import the P12 file!", comment: "")
                    alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                    alert.runModal()
                }
            } else {
                self.errorLabel.isHidden = false
            }
        }
    }
    
    //MARK: NSTextFieldDelegate
    func controlTextDidChange(_ obj: Notification) {
        
        self.updateTextFiedState()
        
        let textField = obj.object;
        if self.passwordTextFiled.isEqual(textField) {
            self.filesTextFiled.updateState(false)
        }
        self.errorLabel.isHidden = true
    }
    
}