#import <Foundation/Foundation.h>
#import "RNApxorEventEmitter.h"
#import "ApxorSDK/APXController.h"

@implementation RNApxorEventEmitter {
    bool hasListeners;
}

RCT_EXPORT_MODULE(APXRNEventEmitter)

- (instancetype)init {
    self = [super init];
    if (self) {
        [[APXController sharedController] registerForEventWithType:APXEventTypeInternal listener:self];
        hasListeners = NO;
    }
    return self;
}

- (void)onEvent:(APXEvent *)event {
    if (event.eventType == APXEventTypeInternal && [event.identifier isEqual: @"embed_card_dimensions_set"]) {
        NSDictionary *dimensions = event.getAdditionalInfo;
        [self sendEvent:dimensions name:@"EmbedCardDimensionsSet"];
    }
    if (event.eventType == APXEventTypeInternal && [event.identifier isEqual: @"remove_place_holder"]) {
        NSDictionary *dimensions = event.getAdditionalInfo;
        [self sendEvent:dimensions name:@"RemovePlaceHolder"];
    }
    if (event.eventType == APXEventTypeInternal && [event.identifier isEqual: @"canShow"]) {
        NSDictionary *info = [event getAdditionalInfo];
        NSLog(@"Event Data is %@",info);
        [self sendEvent:info name:event.identifier];
    } else if (event.eventType == APXEventTypeInternal && [event.identifier isEqualToString:@"removeStoryPlaceHolder"]) {
        NSDictionary *info = [event getAdditionalInfo];
        NSLog(@"Event Data is %@",info);
        [self sendEvent:info name:event.identifier];
    }
}

- (void)sendEvent:(NSDictionary *)dimensions name:(NSString *)eventName {
    if (hasListeners) {
        [self sendEventWithName:eventName body:dimensions];
    }
}

// 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
}

- (NSArray<NSString *> *)supportedEvents {
    return @[@"EmbedCardDimensionsSet", @"RemovePlaceHolder", @"canShow", @"removeStoryPlaceHolder"];
}


+ (BOOL)requiresMainQueueSetup {
    return YES;
}

@end
