//
//  LNEventDeliver.swift
//  Lanu
//
//  Created by OneeChan on 2025/11/6.
//

import Foundation

protocol LNAppMainEvent {
    func onAppLaunchFinished()
    func onAppLanguageChanged(newLanguage: LNAppLanguage)
    func onAppStateChanged(foreground: Bool)
}
extension LNAppMainEvent {
    func onAppLaunchFinished() {}
    func onAppLanguageChanged(newLanguage: LNAppLanguage) {}
    func onAppStateChanged(foreground: Bool) { }
}

class LNEventDeliver {
    private static let lock = NSLock()
    private static let observers = NSHashTable<AnyObject>.weakObjects()
    
    static func addObserver(_ observer: AnyObject) {
        lock.lock()
        guard !observers.contains(observer) else {
            lock.unlock()
            return
        }
        observers.add(observer)
        lock.unlock()
    }
    
    static func removeObserver(_ observer: AnyObject) {
        lock.lock()
        guard observers.contains(observer) else {
            lock.unlock()
            return
        }
        observers.remove(observer)
        lock.unlock()
    }
    
    static func notifyEvent(_ queue: DispatchQueue = .main,
                            _ event: @escaping (AnyObject) -> Void) {
        lock.lock()
        let allObservers = observers.allObjects
        lock.unlock()
        
        if queue == .main, Thread.isMainThread {
            allObservers.forEach { event($0) }
        } else {
            queue.async {
                allObservers.forEach { event($0) }
            }
        }
    }
}

// 主要事件的通知方法
extension LNEventDeliver {
    static func notifyAppLaunchFinished() {
        notifyEvent { ($0 as? LNAppMainEvent)?.onAppLaunchFinished() }
    }
}
