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

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

@implementation BroadcastEventEmitter

RCT_EXPORT_MODULE();

- (instancetype)init {
    self = [super init];
    if (self) {
        // Listen for the broadcast started notification
        CFNotificationCenterAddObserver(
            CFNotificationCenterGetDarwinNotifyCenter(),
            (__bridge const void *)(self),
            broadcastEventCallback,
            (__bridge CFStringRef)BroadcastStartedNotification,
            NULL,
            CFNotificationSuspensionBehaviorDeliverImmediately
        );

        // Listen for the broadcast stopped notification
        CFNotificationCenterAddObserver(
            CFNotificationCenterGetDarwinNotifyCenter(),
            (__bridge const void *)(self),
            broadcastEventCallback,
            (__bridge CFStringRef)BroadcastStoppedNotification,
            NULL,
            CFNotificationSuspensionBehaviorDeliverImmediately
        );
    }
    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;
    [self sendEventWithName:eventName body:nil];
}

// 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 {
    CFNotificationCenterRemoveEveryObserver(
        CFNotificationCenterGetDarwinNotifyCenter(),
        (__bridge const void *)(self)
    );
}

@end
