#import "BroadcastEventEmitter.h"
#import "RTKLogger.h"
#import <React/RCTLog.h>

// Define the notification names
NSString *const BroadcastStartedNotification = @"iOS_BroadcastStarted";
NSString *const BroadcastStoppedNotification = @"iOS_BroadcastStopped";

@implementation BroadcastEventEmitter
{
    bool hasListeners;
}

- (BOOL)canSendEvents {
    return self.bridge != nil;
}

// Will be called when this module's first listener is added.
-(void)startObserving {
    hasListeners = YES;
}

// Will be called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
    hasListeners = NO;
}

RCT_EXPORT_MODULE();

- (instancetype)init {
    self = [super init];
    if (self) {
        [RTKLogger debug:@"BroadcastEventEmitter: Initializing and registering Darwin notification observers"];
        // Listen for the broadcast started notification
        CFNotificationCenterAddObserver(
            CFNotificationCenterGetDarwinNotifyCenter(),
            (__bridge const void *)(self),
            broadcastEventCallback,
            (__bridge CFStringRef)BroadcastStartedNotification,
            NULL,
            CFNotificationSuspensionBehaviorDeliverImmediately
        );
        [RTKLogger debug:@"BroadcastEventEmitter: Registered observer for %@", BroadcastStartedNotification];

        // Listen for the broadcast stopped notification
        CFNotificationCenterAddObserver(
            CFNotificationCenterGetDarwinNotifyCenter(),
            (__bridge const void *)(self),
            broadcastEventCallback,
            (__bridge CFStringRef)BroadcastStoppedNotification,
            NULL,
            CFNotificationSuspensionBehaviorDeliverImmediately
        );
        [RTKLogger debug:@"BroadcastEventEmitter: Registered observer for %@", BroadcastStoppedNotification];
    }
    return self;
}

// Callback for Darwin notifications
void broadcastEventCallback(CFNotificationCenterRef center,
                            void *observer,
                            CFNotificationName name,
                            const void *object,
                            CFDictionaryRef userInfo) {
    BroadcastEventEmitter *eventEmitter = (__bridge BroadcastEventEmitter *)observer;
    [eventEmitter handleNotification:name];
}

// Handle incoming notifications and send events to React Native
- (void)handleNotification:(CFNotificationName)name {
    NSString *eventName = (__bridge NSString *)name;
    [RTKLogger debug:@"BroadcastEventEmitter: Received Darwin notification: %@", eventName];
    if (hasListeners && [self canSendEvents]) {
        [RTKLogger debug:@"BroadcastEventEmitter: Sending event to React Native: %@", eventName];
        [self sendEventWithName:eventName body:nil];
    } else {
        [RTKLogger warning:@"BroadcastEventEmitter: Cannot send event %@ - hasListeners: %d, canSendEvents: %d", eventName, hasListeners, [self canSendEvents]];
    }
}

// Declare the supported event names
- (NSArray<NSString *> *)supportedEvents {
    return @[BroadcastStartedNotification, BroadcastStoppedNotification];
}

// Ensure setup happens on the main queue
+ (BOOL)requiresMainQueueSetup {
    return YES;
}

// Remove observers on deallocation
- (void)dealloc {
    [RTKLogger debug:@"BroadcastEventEmitter: Removing all Darwin notification observers"];
    CFNotificationCenterRemoveEveryObserver(
        CFNotificationCenterGetDarwinNotifyCenter(),
        (__bridge const void *)(self)
    );
}

@end
