//
//  AlanEventEmitter.m
//
//  Created by Alan AI, Inc on 30.10.2019.
//

#import "AlanEventEmitter.h"

@implementation AlanEventEmitter
{
    bool hasListeners;
}

RCT_EXPORT_MODULE();

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        [self subscribe];
    }
    return self;
}

+ (BOOL)requiresMainQueueSetup
{
    return NO;
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

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

- (void)startObserving
{
    hasListeners = YES;
}

- (void)stopObserving
{
    hasListeners = NO;
}

- (void)subscribe
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleEvent:) name:@"kAlanSDKEventNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleConnectState:) name:@"kAlanSDKConnectStateNotification" object:nil];
}

- (void)handleConnectState:(NSNotification*)notification
{
//    NSDictionary *userInfo = notification.userInfo;
//    RCTLogInfo(@"handleConnectState - %@", userInfo);
}

- (void)handleEvent:(NSNotification*)notification
{
    NSDictionary *userInfo = notification.userInfo;
    if( userInfo == nil)
    {
        return;
    }
    NSString *jsonString = [userInfo objectForKey:@"jsonString"];
    if( jsonString == nil)
    {
        return;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error = nil;
    id unwrapped = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if( error != nil)
    {
        return;
    }
    if( ![unwrapped isKindOfClass:[NSDictionary class]] )
    {
        return;
    }
    NSDictionary *d = [NSDictionary dictionaryWithDictionary:unwrapped];
    NSDictionary *data = [d objectForKey:@"data"];
    if( data == nil )
    {
        return;
    }
    
    if( hasListeners )
    {
         [self sendEventWithName:@"command" body:data];
    }
}

@end
