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

import Cocoa

class DSignatureCreateInfoViewController: NSViewController, NSTextFieldDelegate {

    @IBOutlet weak var contendView: NSView!
    
    @IBOutlet weak var titleLabel: NSTextField!

    @IBOutlet weak var nameLabel: NSTextField!
    @IBOutlet weak var organizationLabel: NSTextField!
    @IBOutlet weak var organizationUnitLabel: NSTextField!
    @IBOutlet weak var emailLabel: NSTextField!
    @IBOutlet weak var countryLabel: NSTextField!
    @IBOutlet weak var purposeLabel: NSTextField!
    
    @IBOutlet weak var nameTextFiled: NSTextField!
    @IBOutlet weak var organizationTextFiled: NSTextField!
    @IBOutlet weak var organizationUnitTextFiled: NSTextField!
    @IBOutlet weak var emailTextFiled: NSTextField!
    @IBOutlet weak var countryButton: NSPopUpButton!
    @IBOutlet weak var purposeButton: NSPopUpButton!
    @IBOutlet weak var errorLabel: NSTextField!
    
    @IBOutlet weak var promptBox: NSBox!
    @IBOutlet var promptTextView: NSTextView!
    
    @IBOutlet weak var previousStepButton: NSButton!
    @IBOutlet weak var continueButton: NSButton!

    @IBOutlet weak var textFieldLeftConst: NSLayoutConstraint!
    @IBOutlet weak var countryBtnTopConst: NSLayoutConstraint!
    
    
//    @property(nonatomic) IBOutlet NSLayoutConstraint *bottomOffset;
//
//    @property(nonatomic) IBOutlet NSLayoutConstraint *leftBottomOffset;
    
    var codes: [String] = []
    var actionBlock: ((_ createVC:DSignatureCreateInfoViewController, _ action:DSignatureActionType, _ cer:NSDictionary, _ certUsage:Int)->Void)?
    
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
        self.updateButtonState()
        self.errorLabel.isHidden = true
        
        self.nameTextFiled.delegate = self
        self.emailTextFiled.delegate = self
        self.organizationTextFiled.delegate = self
        self.organizationUnitTextFiled.delegate = self
        
        self.purposeButton.addItems(withTitles: [NSLocalizedString("Digital Signature", comment: ""),
                                                 NSLocalizedString("Data Encryption", comment: ""),
                                                 NSLocalizedString("Digital Signatures and Data Encryption", comment: "")])
        
        self.reloadData()
        
        self.nameTextFiled.wantsLayer = true
        self.organizationTextFiled.wantsLayer = true
        self.organizationUnitTextFiled.wantsLayer = true
        self.emailTextFiled.wantsLayer = true
        
        self.nameTextFiled.layer?.borderWidth = 1.0
        self.organizationTextFiled.layer?.borderWidth = 1.0
        self.organizationUnitTextFiled.layer?.borderWidth = 1.0
        self.emailTextFiled.layer?.borderWidth = 1.0
        
        self.nameTextFiled.layer?.cornerRadius = 5.0
        self.organizationTextFiled.layer?.cornerRadius = 5.0
        self.organizationUnitTextFiled.layer?.cornerRadius = 5.0
        self.emailTextFiled.layer?.cornerRadius = 5.0
        
        self.organizationTextFiled.layer?.borderColor = NSColor(red: 2.0/255.0, green: 8.0/255.0, blue: 38.0/255.0, alpha: 0.15).cgColor
        self.organizationUnitTextFiled.layer?.borderColor = NSColor(red: 2.0/255.0, green: 8.0/255.0, blue: 38.0/255.0, alpha: 0.15).cgColor
        
        self.localizedLanguage()
        
        self.nameTextFiled.layer?.borderColor = NSColor.clear.cgColor
        self.emailTextFiled.layer?.borderColor = NSColor.clear.cgColor
    }
    
    func reloadData() {
        
        var countryCodes = NSLocale.isoCountryCodes 
        self.codes = countryCodes
        
        var codes: [String] = []
        let localeID = NSLocale.current.identifier
        let components = NSLocale.components(fromLocaleIdentifier: localeID)
        let countryCode = components[NSLocale.Key.countryCode.rawValue]
        
        for countryCode in countryCodes {
            let identifier = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: countryCode])
            let local = NSLocale(localeIdentifier: localeID)
            
            let country = local.displayName(forKey: NSLocale.Key.identifier, value: identifier)
            codes.append(String(format: "%@ - %@", countryCode, (country ?? "")))
        }
        
        self.countryButton.addItems(withTitles: codes)
        
        for index in 0...countryCodes.count-1 {
            let cCode = countryCodes[index]
            if countryCode == cCode {
                self.countryButton.selectItem(at: index)
            }
        }
        
        let sud = UserDefaults.standard
        let loginName = NSFullUserName()
        if loginName.isEmpty == false {
            self.nameTextFiled.stringValue = loginName
        }
        
        self.organizationTextFiled.stringValue = sud.string(forKey: CAuthenticationDepartmentKey) ?? ""
        self.organizationUnitTextFiled.stringValue = sud.string(forKey: CAuthenticationCompanyNameKey) ?? ""
        self.emailTextFiled.stringValue = sud.string(forKey: CAuthenticationEmailAddressKey) ?? ""
        
    }
    
    func localizedLanguage() {
        self.titleLabel.stringValue = NSLocalizedString("Create a Self-signed Digital ID", comment: "")
        
        self.nameLabel.stringValue = NSLocalizedString("Name", comment: "")
        self.organizationLabel.stringValue = NSLocalizedString("Organization Name", comment: "")
        self.organizationUnitLabel.stringValue = NSLocalizedString("Organization Unit", comment: "")
        self.emailLabel.stringValue = NSLocalizedString("Email Address", comment: "")
        self.countryLabel.stringValue = NSLocalizedString("Country/Region", comment: "")
        self.purposeLabel.stringValue = NSLocalizedString("Purpose", comment: "")
        
        var maxLabelWidth = self.nameLabel.sizeThatFits(CGSize(width: 1000, height: self.nameLabel.frame.size.height)).width
        if self.organizationLabel.sizeThatFits(CGSize(width: 1000, height: self.organizationLabel.frame.size.height)).width > maxLabelWidth {
            maxLabelWidth = self.organizationLabel.sizeThatFits(CGSize(width: 1000, height: self.organizationLabel.frame.size.height)).width
        }
        if self.organizationUnitLabel.sizeThatFits(CGSize(width: 1000, height: self.organizationUnitLabel.frame.size.height)).width > maxLabelWidth {
            maxLabelWidth = self.organizationUnitLabel.sizeThatFits(CGSize(width: 1000, height: self.organizationUnitLabel.frame.size.height)).width
        }
        if self.emailLabel.sizeThatFits(CGSize(width: 1000, height: self.emailLabel.frame.size.height)).width > maxLabelWidth {
            maxLabelWidth = self.emailLabel.sizeThatFits(CGSize(width: 1000, height: self.emailLabel.frame.size.height)).width
        }
        if self.countryLabel.sizeThatFits(CGSize(width: 1000, height: self.countryLabel.frame.size.height)).width > maxLabelWidth {
            maxLabelWidth = self.countryLabel.sizeThatFits(CGSize(width: 1000, height: self.countryLabel.frame.size.height)).width
        }
        if self.purposeLabel.sizeThatFits(CGSize(width: 1000, height: self.purposeLabel.frame.size.height)).width > maxLabelWidth {
            maxLabelWidth = self.purposeLabel.sizeThatFits(CGSize(width: 1000, height: self.purposeLabel.frame.size.height)).width
        }
        if maxLabelWidth < 90 {
            maxLabelWidth = 90
        }
        self.textFieldLeftConst.constant = maxLabelWidth + 10

        self.promptTextView.string = String(format: "%@\n\n%@",NSLocalizedString("Enter the identity information to be used for creating the self-signed digital ID.",  comment: ""), NSLocalizedString("Digital IDs that are self-signed by individuals do not provide the assurance that the identity information is valid. For this reason they may not be accepted in some use cases.", comment: ""))
        self.nameTextFiled.placeholderString = NSLocalizedString("Enter name...", comment: "");
        self.errorLabel.stringValue = NSLocalizedString("Email address is not valid", comment: "");
        self.organizationTextFiled.placeholderString = NSLocalizedString("Enter organization name...", comment: "");
        self.organizationUnitTextFiled.placeholderString = NSLocalizedString("Enter organization unit...", comment: "");
        self.emailTextFiled.placeholderString = NSLocalizedString("Enter Email", comment: "");

        self.previousStepButton.title = NSLocalizedString("Previous Step", comment: "");
        self.continueButton.title = NSLocalizedString("Continue",  comment: "");
    }
    
    func validateEmail(_ strEmail: String) -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest: NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailTest.evaluate(with: strEmail)
    }
    
    func updateButtonState() {
        if self.nameTextFiled.stringValue.isEmpty == false && self.validateEmail(self.emailTextFiled.stringValue) {
            self.continueButton.isEnabled = true
        } else {
            self.continueButton.isEnabled = false
        }
    }
    
    func updateTextFiedState() {
        if self.nameTextFiled.stringValue.isEmpty == false {
            self.nameTextFiled.updateState(false)
        } else {
            self.nameTextFiled.updateState(true)
        }
        
        if self.emailTextFiled.stringValue.isEmpty == false {
            self.emailTextFiled.updateState(false)
        } else {
            self.emailTextFiled.updateState(true)
        }
    }
    
    
    //MARK: IBAction
    
    @IBAction func closeAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .cancel, NSDictionary(), 0)
    }
    
    @IBAction func previousAction(_ sender: Any) {
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .previousStep, NSDictionary(), 0)
    }
    
    @IBAction func continueAction(_ sender: Any) {
        self.view.window?.makeFirstResponder(nil)
        
        if self.validateEmail(self.emailTextFiled.stringValue) == false {
            return
        }
        
        let cer = NSMutableDictionary.init()
        
        cer.setValue(self.nameTextFiled.stringValue, forKey: "CN")
        cer.setObject(self.emailTextFiled.stringValue, forKey: "emailAddress" as NSCopying)
        if self.codes.count > self.countryButton.indexOfSelectedItem {
            let string = self.codes[self.countryButton.indexOfSelectedItem]
            cer.setValue(string, forKey: "C")
        }
        if self.organizationTextFiled.stringValue.isEmpty == false {
            cer.setValue(self.organizationTextFiled.stringValue, forKey: "O")
        }
        if self.organizationUnitTextFiled.stringValue.isEmpty == false {
            cer.setValue(self.organizationUnitTextFiled.stringValue, forKey: "OU")
        }
        
        let dex = self.purposeButton.index(of: self.purposeButton.selectedItem!)
        
        guard let callBack = self.actionBlock else {
            return
        }
        callBack(self, .confirm, cer, dex)
    }
    
    //MARK: NSTextFieldDelegate
    func controlTextDidChange(_ obj: Notification) {

        self.updateButtonState()
        
        if obj.object == nil {
            return
        }
            
        let textField = obj.object as! NSTextField
        if self.emailTextFiled.isEqual(textField) ||
            self.nameTextFiled.isEqual(textField) {
            if (textField.stringValue.isEmpty == false) {
                textField.updateState(false)
            } else {
                textField.updateState(true)
            }
        }
        
        if self.emailTextFiled.isEqual(textField) {
            self.errorLabel.isHidden = true
            
            self.countryBtnTopConst.constant = 16.0;
        }
    }

    func controlTextDidEndEditing(_ obj: Notification) {

        let fied: NSTextField = obj.object as! NSTextField;
        if fied.isEqual(self.emailTextFiled) {
            if self.validateEmail(self.emailTextFiled.stringValue) == true {
                self.errorLabel.isHidden = true
                self.countryBtnTopConst.constant = 16.0;
            } else {
                self.errorLabel.isHidden = false;
                self.countryBtnTopConst.constant = self.errorLabel.frame.size.height + 12;
            }
        }
    }
}