//
//  DetectObserver.swift
//  GenjiAPITest
//
//

import Foundation
import Combine

// Expose the Objective-C notification name to Swift
extension NSNotification.Name {
    static let genjiAPIRemoveNotification = NSNotification.Name("GenjiAPIRemove")
    static let genjiAPIConnectNotification = NSNotification.Name("GenjiAPIConnect")
}

class NotificationObserver: ObservableObject, @unchecked Sendable{
    @Published var notificationReceived:Int = 0
    
    private var cancellables = Set<AnyCancellable>()

    init() {
        observeNotification()
    }

    func countDown() {
        self.notificationReceived = 0
    }
    
    func observeNotification() {
        
        notificationReceived = 0
        
        NotificationCenter.default.publisher(for: .genjiAPIRemoveNotification)
            .receive(on: DispatchQueue.main) // Ensure UI updates are on the main thread
            .sink { [weak self] _ in
                debugPrint("Remove Notification received ")
                self?.notificationReceived = 1
                NotificationCenter.default.post(name: Notification.Name("DonglesChanged"), object: nil)
                
                Timer.scheduledTimer(withTimeInterval: 10.0, repeats:false,  block:{ [weak self] _ in
                    self?.notificationReceived = 0
                })
            }
            .store(in: &cancellables)
        
        NotificationCenter.default.publisher(for: .genjiAPIConnectNotification)
            .receive(on: DispatchQueue.main) // Ensure UI updates are on the main thread
            .sink { [weak self] _ in
                debugPrint("Connect Notification received")
                self?.notificationReceived = 2
                NotificationCenter.default.post(name: Notification.Name("DonglesChanged"), object: nil)

                Timer.scheduledTimer(withTimeInterval: 10.0, repeats:false,  block:{ [weak self] _ in
                    self?.notificationReceived = 0
                })
            }
            .store(in: &cancellables)
    }
    


}
