//
//  BaseXibView.swift
//  KMComponentLibrary
//
//  Created by wanjun on 2024/6/6.
//

import Cocoa
import AppKit

@objcMembers
public class BaseXibView: NSView {
    
    @IBOutlet var contentView: NSView!
    
    deinit {
        KMPrint(self.className + " deinit.")
        
        self.removeNotifations()
    }
    
    // MARK: 初始化
    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        
        initContentView()
        addNotifations()
    }
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initContentView()
        addNotifations()
    }
    
    private func addNotifations() {
        updateUIThemeColor()
        NotificationCenter.default.addObserver(self, selector: #selector(updateUIThemeColor), name: APPAppearanceChangedNotificationName, object: nil)
        
        updateUILanguage()
        NotificationCenter.default.addObserver(self, selector: #selector(updateUILanguage), name: APPLanguageChangedNotificationName, object: nil)
    }
    
    private func removeNotifations() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func updateUIThemeColor() {}
    
    @objc func updateUILanguage() {}
    
    private func initContentView() {
        let isExist = Bundle.main.path(forResource: String(describing:self.classForCoder.self), ofType: "nib")
        if isExist != nil {
            var topLevelArray: NSArray? = nil
            let resource = NSNib(nibNamed: String(describing:self.classForCoder.self), bundle: Bundle(for: self.classForCoder.self))
            
            if resource != nil {
                if (resource!.instantiate(withOwner: self, topLevelObjects: &topLevelArray)) {
                    for view in topLevelArray! {
                        if view is NSView {
                            contentView = view as? NSView
                            break
                        }
                    }
                }
                
                if contentView == nil {
                    contentView = NSView()
                }
                addSubview(contentView)
                contentView.translatesAutoresizingMaskIntoConstraints = false
                NSLayoutConstraint.activate([
                    contentView.topAnchor.constraint(equalTo: topAnchor),
                    contentView.leftAnchor.constraint(equalTo: leftAnchor),
                    contentView.rightAnchor.constraint(equalTo: rightAnchor),
                    contentView.bottomAnchor.constraint(equalTo: bottomAnchor)])
                contentView.updateConstraintsForSubtreeIfNeeded()
            }
        }
    }
}