/// RNBridgeObserver.swift
/// This class observes the React Native bridge state and notifies the delegate when the app becomes active or inactive.
/// It is used to manage the state of the BlueStack SDK initialization process.

import Foundation
import React

protocol RNBridgeObserverDelegate: AnyObject {
    func onBridgeActive()
    func onBridgeInactive()
}

@objc(RNBridgeObserver)
class RNBridgeObserver: RCTEventEmitter {
    private static let TAG = "RNBridgeObserver"
    private var isAppActive = false
    private var hasListeners = false
    weak var delegate: RNBridgeObserverDelegate?

    override init() {
        BlueStackLogger.debug(tag: Self.TAG, message: "init")
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(onAppDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onAppWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
    }

    deinit {
        BlueStackLogger.debug(tag: Self.TAG, message: "deinit")
        NotificationCenter.default.removeObserver(self)
    }

    @objc private func onAppDidBecomeActive() {
        BlueStackLogger.debug(tag: Self.TAG, message: "App did become active")
        isAppActive = true
        notifyBridgeState()
    }

    @objc private func onAppWillResignActive() {
        BlueStackLogger.debug(tag: Self.TAG, message: "App will resign active")
        isAppActive = false
        notifyBridgeState()
    }

    override func startObserving() {
        BlueStackLogger.debug(tag: Self.TAG, message: "RCTEventEmitter startObserving")
        hasListeners = true
        notifyBridgeState()
    }

    override func stopObserving() {
        BlueStackLogger.debug(tag: Self.TAG, message: "RCTEventEmitter stopObserving")
        hasListeners = false
        notifyBridgeState()
    }

    override func supportedEvents() -> [String] {
        return [] // Subclasses should override this to provide supported events
    }

    private func notifyBridgeState() {
        BlueStackLogger.debug(tag: Self.TAG, message: "Notifying bridge state: isAppActive = \(isAppActive), hasListeners = \(hasListeners)")
        // Notify the delegate about the bridge state
        if isAppActive && hasListeners {
            delegate?.onBridgeActive()
        } else {
            delegate?.onBridgeInactive()
        }
    }
}
