//
//  KMUserFbEmailItemView.swift
//  PDF Reader Pro Edition
//
//  Created by tangchao on 2024/7/11.
//

import Cocoa

class KMUserFbEmailItemView: NSView, NibLoadable {
    @IBOutlet weak var titleLabel: NSTextField!
    @IBOutlet weak var box: NSBox!
    @IBOutlet weak var textfiled: KMTextField!
    @IBOutlet weak var tipLabel: NSTextField!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let title = NSLocalizedString("Email", comment: "")
        let attri = NSMutableAttributedString(string: title)
        attri.addAttribute(.font, value: NSFont.systemFont(ofSize: 13), range: NSMakeRange(0, title.count))
        
        attri.append(.init(string: "*", attributes: [NSAttributedString.Key.font : NSFont.systemFont(ofSize: 13), NSAttributedString.Key.foregroundColor : NSColor(red: 250/255.0, green: 31/255.0, blue: 93/255.0, alpha: 1.0)]))
        
        self.titleLabel.attributedStringValue = attri
        
        self.box.borderWidth = 1
        self.box.borderColor = NSColor(white: 0, alpha: 0.2)
        self.box.fillColor = .white
        self.textfiled.drawsBackground = false
        self.textfiled.isBordered = false
//        self.textfiled.focusRingType = .none
        self.textfiled.placeholderString = NSLocalizedString("Your email", comment: "")
        self.textfiled.delegate = self
        self.textfiled.wantsLayer = true
        self.textfiled.layer?.cornerRadius = 4
        self.textfiled.layer?.masksToBounds = true
        
        self.textfiled.firstResponderHandler = { [weak self] result in
            if result {
                self?.box.borderColor = NSColor.km_init(hex: "#1770F4")
            } else {
                self?.box.borderColor = NSColor(white: 0, alpha: 0.2)
            }
        }
        
        
        self.tipLabel.textColor = NSColor.km_init(hex: "#FA1E5D")
        self.tipLabel.font = NSFont(name: "SFProText-Regular", size: 11)
        self.tipLabel.isHidden = true
    }
    
    func string() -> String {
        return self.textfiled.stringValue
    }
    
    func showTip(label: String) {
        self.window?.makeFirstResponder(self.textfiled)
        self.box.horLightShakeAnimation()
        
        self.tipLabel.stringValue = label
        self.tipLabel.isHidden = false
    }
    
    func hiddenTip() {
        self.tipLabel.isHidden = true
    }
}

extension KMUserFbEmailItemView: NSTextFieldDelegate {
    
    func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
        return true
    }
    
    func controlTextDidBeginEditing(_ obj: Notification) {
        
    }
    
    func controlTextDidEndEditing(_ obj: Notification) {
        if self.textfiled.isEqual(to: obj.object) {
            self.box.borderColor = NSColor(white: 0, alpha: 0.2)
        }
    }
    func controlTextDidChange(_ obj: Notification) {
        if self.textfiled.isEqual(to: obj.object) {
            self.hiddenTip()
        }
    }
}