

#import <React/RCTEventEmitter.h>

@interface CTPEventEmitter : RCTEventEmitter <RCTBridgeModule>

- (bool)sendEvent:(NSString*) eventName body:(NSDictionary*) body;
- (bool)hasListeners;


@end



@implementation CTPEventEmitter
{
  bool hasListeners;
}

RCT_EXPORT_MODULE(CTPEventEmitter);

+ (id)allocWithZone:(NSZone *)zone {
  static CTPEventEmitter *sharedInstance = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    sharedInstance = [super allocWithZone:zone];
  });
  return sharedInstance;
}

// Will be called when this module's first listener is added.
-(void)startObserving {
  hasListeners = YES;
  // Set up any upstream listeners or background tasks as necessary
}

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

-(bool)hasListeners {
  return hasListeners;
}

// Returns list of all event Names this topic can export
-(NSArray<NSString *> *)supportedEvents{
  return @[@"onReady",@"onKeyValidation",@"onFacilityUpdate", @"onNavigationUpdate"];
}

-(bool)sendEvent:(NSString*) eventName body:(NSDictionary*) body {
//  [self sendEventName:@"onNavigationUpdate" body:@{@"key": @"value"}];
  
  if (hasListeners) {
    NSLog(@"CustomEventsEmitter sendEventName emitting event: %@", eventName);
    [self sendEventWithName:eventName body:body];
  } else {
    NSLog(@"CustomEventsEmitter sendEventName called without listeners: %@", eventName);
  }
  return TRUE;
}

//- (void)sendEventName:(NSString *)eventName body:(id)body {
//  if (hasListeners) {
//    NSLog(@"CustomEventsEmitter sendEventName emitting event: %@", eventName);
//    [self sendEventWithName:eventName   body:body];
//  } else {
//    NSLog(@"CustomEventsEmitter sendEventName called without listeners: %@", eventName);
//  }
//}



@end
