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

import Cocoa

class DSignatureSaveFolderViewController: NSViewController, NSTextFieldDelegate {

    
    @IBOutlet weak var titleLabel: NSTextField!
    @IBOutlet weak var subTitleLabel: NSTextField!
    
    @IBOutlet weak var filesLabel: NSTextField!
    @IBOutlet weak var passwordLabel: NSTextField!
    @IBOutlet weak var confirmPasswordLabel: NSTextField!
    @IBOutlet weak var filesTextField: NSTextField!
    @IBOutlet weak var passwordTextField: NSSecureTextField!
    @IBOutlet weak var confirmPasswordTextField: NSSecureTextField!
    @IBOutlet weak var errorLabel: NSTextField!
    @IBOutlet weak var openFileButton: NSButton!
    
    @IBOutlet weak var promptBox: NSBox!
    @IBOutlet var promptTextView: NSTextView!
    
    @IBOutlet weak var cancelButton: NSButton!
    @IBOutlet weak var continueButton: NSButton!
   
//    @property(nonatomic) IBOutlet NSLayoutConstraint *bottomOffset;
    
    
    var actionBlock: ((_ saveFolderVC: DSignatureSaveFolderViewController, _ actionType: DSignatureActionType, _ infoDic: NSDictionary)->Void)?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        self.titleLabel.textColor = NSColor.labelColor
        self.subTitleLabel.textColor = NSColor.labelColor
         
        self.filesLabel.textColor = NSColor.labelColor
        self.passwordLabel.textColor = NSColor.labelColor
        self.confirmPasswordLabel.textColor = NSColor.labelColor
        
        self.filesTextField.textColor = NSColor.labelColor
        self.passwordTextField.textColor = NSColor.labelColor
        self.confirmPasswordTextField.textColor = NSColor.labelColor
        
        self.promptTextView.textColor = NSColor.labelColor
        
//        self.bottomOffset.constant = 25.0;
        self.errorLabel.isHidden = true
        
        self.filesTextField.wantsLayer = true
        self.passwordTextField.wantsLayer = true
        self.confirmPasswordTextField.wantsLayer = true
        self.filesTextField.delegate = self;
        self.filesTextField.isEnabled = false
        
        self.filesTextField.layer?.borderWidth = 1.0
        self.passwordTextField.layer?.borderWidth = 1.0
        self.confirmPasswordTextField.layer?.borderWidth = 1.0;
        
        self.filesTextField.updateState(false)
        self.passwordTextField.layer?.borderColor = NSColor.clear.cgColor
        self.confirmPasswordTextField.layer?.borderColor = NSColor.clear.cgColor
        
        self.filesTextField.layer?.cornerRadius = 5.0
        self.passwordTextField.layer?.cornerRadius = 5.0
        self.confirmPasswordTextField.layer?.cornerRadius = 5.0;
        
        self.filesTextField.delegate = self
        self.confirmPasswordTextField.delegate = self
        
        self.localizedLanguage()
        
        if self.filesTextField.stringValue.isEmpty == false {
            self.continueButton.isEnabled = true
        } else {
            self.continueButton.isEnabled = false
        }
    }

    func localizedLanguage() {
        self.titleLabel.stringValue = NSLocalizedString("Save the Self-signed Digital ID to a File", comment: "");
        self.subTitleLabel.stringValue = NSLocalizedString("Your digital ID will be saved at the following location :", comment: "")
        self.filesLabel.stringValue = NSLocalizedString("File", comment: "");
        self.passwordLabel.stringValue = NSLocalizedString("Password", comment: "")
        self.confirmPasswordLabel.stringValue = NSLocalizedString("Confirm the Password", comment: "")

        self.promptTextView.string = String(format: "%@\n\n%@",NSLocalizedString("Add a password to protect the private key of the digital ID. You will need this password again to use the digital ID for signing.", comment: ""), NSLocalizedString("Save the digital ID file in a known location so that you can copy or backup it.", comment: ""))
        
        self.cancelButton.title = NSLocalizedString("Previous Step", comment: "")
        self.continueButton.title = NSLocalizedString("Continue", comment: "")
        self.openFileButton.title = String(format: "%@",NSLocalizedString("Browse", comment: ""))
        self.errorLabel.stringValue = NSLocalizedString("Passwords do not match", comment: "")
    }
    
    func getUniqueFilePath(_ filePath: String) -> (String) {
        var i = 0
        var isDirectory: ObjCBool = false
        var uniqueFilePath = filePath
        
        let filemanager = FileManager.default
        filemanager.fileExists(atPath: uniqueFilePath, isDirectory: &isDirectory)
        if isDirectory.boolValue {
            while filemanager.fileExists(atPath: uniqueFilePath) {
                i += 1
                uniqueFilePath = String(format: "%@(%d)", filePath, i)
            }
        } else {
            while filemanager.fileExists(atPath: uniqueFilePath) {
                i += 1
                let fileURL = URL(fileURLWithPath: filePath)
                let path = String(format: "%@(%d)", fileURL.deletingPathExtension().path, i)
                uniqueFilePath = String(format: "%@.%@", path, fileURL.pathExtension)
            }
        }
        
        return uniqueFilePath
    }
    
    
    //MARK: IBAction
    @IBAction func penFile(_ sender: Any) {
        let accessoryCtr = PDFCertExportAccessoryView.init()
        
        let openPanel = NSOpenPanel()
        openPanel.accessoryView = accessoryCtr.view
        openPanel.canChooseDirectories = true
        openPanel.canChooseFiles = false
        openPanel.beginSheetModal(for: self.view.window!) { result in
            if result == .OK {
                let outputULR = openPanel.url!
                var filePath = outputULR.path
                if accessoryCtr.formatMatrix.selectedRow == 0 {
                    filePath = filePath + "/Untitled.p12"
                } else {
                    filePath = filePath + "/Untitled.pfx"
                }
                self.filesTextField.stringValue = self.getUniqueFilePath(filePath)
                
                if self.filesTextField.stringValue.isEmpty {
                    self.filesTextField.updateState(true)
                } else {
                    self.filesTextField.updateState(false)
                }
                
                if self.filesTextField.stringValue.isEmpty == false {
                    self.continueButton.isEnabled = true
                } else {
                    self.continueButton.isEnabled = false
                }
                
            }
            
        }
        
    }
    
    @IBAction func closeAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .cancel, NSDictionary())
    }
    
    @IBAction func previousAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .previousStep, NSDictionary())
    }
    
    @IBAction func continueAction(_ sender: Any) {
        self.view.window?.makeFirstResponder(nil)
        if self.filesTextField.stringValue.count < 1 {
            return
        }
        if self.confirmPasswordTextField.stringValue == self.passwordTextField.stringValue {
            var isDir: ObjCBool = false
            
            let filePath = URL(fileURLWithPath: self.filesTextField.stringValue)
            let parentDirectory = filePath.deletingLastPathComponent().path

            let isExists = FileManager.default.fileExists(atPath: parentDirectory, isDirectory: &isDir)
            if isDir.boolValue == false || isExists == false {
                let alert = NSAlert.init()
                alert.messageText = NSLocalizedString("Output Folder can not be empty.", comment: "")
                alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                alert.runModal()
                return
            }
            let dic = NSMutableDictionary()
            dic.setValue(self.filesTextField.stringValue, forKey: SAVEFILEPATH_KEY)
            if self.passwordTextField.stringValue.count > 0 {
                dic.setValue(self.passwordTextField.stringValue, forKey: PASSWORD_KEY)
            }
            self.errorLabel.isHidden = true
//            self.bottomOffset.constant = 25.0;
            
            guard let callBack = self.actionBlock else {
                return
            }
            callBack(self, .confirm, dic)
        } else {
            self.errorLabel.isHidden = false
//            self.bottomOffset.constant = self.errorLabel.frame.size.height + 10;
        }
    }
    
    //MARK: NSTextFieldDelegate
    func controlTextDidChange(_ obj: Notification) {
        
        if self.filesTextField.stringValue.isEmpty == false {
            self.continueButton.isEnabled = true
        } else {
            self.continueButton.isEnabled = false
        }
        
        let textField = obj.object as! NSTextField
        if self.filesTextField.isEqual(textField) {
            if self.filesTextField.stringValue.isEmpty == false {
                self.filesTextField.updateState(false)
            } else {
                self.filesTextField.updateState(true)
            }
        }
        
        self.errorLabel.isHidden = true
//        self.bottomOffset.constant = 25.0;
    }
}

extension NSTextField {
    func updateState(_ isError: Bool) {
        if isError {
            self.layer?.borderColor = NSColor.systemRed.cgColor
        } else {
            self.layer?.borderColor = NSColor.clear.cgColor
        }
    }
}