#import "EventEmitter.h"

@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 {
  printf("Event Module Got New Listener\n");
  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 {
  printf("Event Module Stopped Observering\n");
  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 @[@"NAVIGATION_PATH_GENERATED",@"USER_POSITION_UPDATED", @"WINDOW_LOADED", @"MAP_TAPPED_GENERIC", @"ODP_READY", @"ODP_KEY_VALIDATION", @"ODP_NAVIGATION_UPDATE", @"ODP_FACILITY_UPDATE",@"GENERATED_SEARCH_DESTINATIONS",@"ERROR",@"VENUE_LOADED",@"GEOFENCES_ENTERED", @"SCREEN_ROTATED",@"GEOFENCES_CHANGED",@"REROUTE_NAVIGATION_PATH_GENERATED"];
}

-(bool)sendEvent:(NSString*) eventName body:(NSObject*) body {
//  [self sendEventName:@"onNavigationUpdate" body:@{@"key": @"value"}];

  
  // [NSThread sleepForTimeInterval:0.1f];
  
  // if (hasListeners) {
    // NSLog(@"CustomEventsEmitter sendEventName emitting event: %@", eventName);
  @try{
    [self sendEventWithName:eventName body:body];
  }
  @catch (NSException * exception){
    printf("Unable to Emit Event. %s", eventName);
    return FALSE;
  }
  @finally {

  }
  return TRUE;
}

@end
