#import "SseClient.h"
#import "RNSseClient-Swift.h"

@implementation SseClient {
  EventManager * manager;
  BOOL hasListeners;
}

RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(connect:(NSString *)headers url:(NSString *)url) {
  manager = [EventManager shared];
  [manager startManagerWithURL:url andHeaders:headers listener:^(NSString * eIdentifier, NSString * eName, id eData) {
    if (self->hasListeners) {
      [self sendEventWithName:@"SseEvent" body: @{@"type": eName, @"data": eData}];
    }
  }];
}

RCT_EXPORT_METHOD(disconnect) {
  manager = [EventManager shared];
  [manager stopManager];
}

// Method called when a listener has start Observing, this method is usually called when a listener is added from RN code.
- (void)   startObserving {
  hasListeners = YES;
}

// Method called when a listener has stoped observing. Needed for performance.
- (void)   stopObserving  {
  hasListeners = NO;
}

// Delegate method for assigning the supported Events, for the moment, only SseEvent is used.
- (NSArray<NSString *> *)supportedEvents {
  return @[@"SseEvent"];
}

@end
