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

@import Clarity;

static NSString *const kClarityEventSessionStarted = @"sessionStarted";
static NSString *const kClaritySessionIdParameter = @"sessionId";

@implementation ClarityEmitter
{
    bool hasListeners;
    bool registeredOnSessionStartedCallback;
}

RCT_EXPORT_MODULE()

- (NSArray<NSString *> *)supportedEvents {
    return @[kClarityEventSessionStarted];
}

// Will be called when this module's first listener is added.
-(void)startObserving {
    hasListeners = YES;

    [self registerOnSessionStartedCallback];
}

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

- (void)registerOnSessionStartedCallback {
    // `setOnSessionStartedCallback` should be called:
    //   - once to maintain the same callback.
    //   - only when there are listeners so that they can receive the first invocation from the SDK.
    if (self->registeredOnSessionStartedCallback) {
        return;
    }

    self->registeredOnSessionStartedCallback = [ClaritySDK setOnSessionStartedCallback:^(NSString * _Nonnull sessionId) {
        if (self->hasListeners) { // Only send events if anyone is listening.
            [self sendEventWithName:kClarityEventSessionStarted body:@{
                kClaritySessionIdParameter: sessionId
            }];
        }
    }];
}

@end
