//
//  LLBlockingEmitter.m
//  LLLocalytics
//
//  Created by Anand Bashyam on 2/24/18.
//  Copyright © 2018 Facebook. All rights reserved.
//

#import "LLBlockingEmitter.h"

@interface LLBlockingEmitter ()
@property (nonatomic) dispatch_semaphore_t responseReceived;
@property (nonatomic) id response;
@end

@implementation LLBlockingEmitter
- (instancetype)init {
    if (self = [super init]) {
        _responseReceived = dispatch_semaphore_create(0);
        return self;
    }
    return nil;
}

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

- (void)respond:(id)response toEvent:(NSString*)eventName {
    // Future proof to support other events we have only 1  possible at a time.
    self.response = response;
    dispatch_semaphore_signal(self.responseReceived);
}

- (void)sendEvent:(NSString*)eventName withData:(id)data andWait:(void(^)(id value))completionHandler {
    [super sendEvent:eventName withData:data];
    dispatch_semaphore_wait(self.responseReceived, DISPATCH_TIME_FOREVER);
    completionHandler(self.response);
}
@end
