//
//  VertcModule.m
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "VolcApiEngine/VolcEventObserver.h"
#import <React/RCTEventEmitter.h>
#import "VolcApiEngine/VolcEventObserver.h"
#import "VertcApiEngine.h"
#import "RTCHeader.h"
#import "RCTVertc.h"
#import "VertcImpl.h"
#import <VertcSpec/VertcSpec.h>

#define EVENT_NAME @"VertcModule:onEvent"

@interface RCTVertc () <NativeVertcSpec>

@end

static RCTVertc *instance = nil;

@implementation RCTVertc  {
  bool hasListeners;
}

+ (instancetype)shareInstance {
  return instance;
}

//@See https://stackoverflow.com/questions/50773748/difference-requiresmainqueuesetup-and-dispatch-get-main-queue
+ (BOOL)requiresMainQueueSetup {
  return YES;
}

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

- (instancetype) init {
  self = [super init];
  if (self) {
    instance = self;
     self.impl = [[VertcImpl alloc] initWithModule: instance];
  }
  return self;
}

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

- (void)onEvent:(NSString *)eventName data:(id)eventData {
  NSDictionary *dic = @{@"event" : eventName, @"data" : eventData};
  [self sendEventWithName:EVENT_NAME body:dic];
}

RCT_EXPORT_MODULE(Vertc)

- (NSNumber *)newApiEngine {
  return [self.impl newApiEngine];
}

- (void)call:(NSString *)params 
    callback: (RCTResponseSenderBlock)callback {
  NSDictionary * args = @{@"params": params};
  [self.impl callApi:args callback:^(id _Nonnull res) {
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:res options:0 error:nil];
    NSString* jsonResult = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    callback(@[jsonResult]);
  }];
}

- (NSString *)callSync: (NSString *) params {
  NSDictionary* args = @{@"params": params};  
  NSDictionary* result = [self.impl callApiSync: args];
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:result options:0 error:nil];
  NSString* jsonResult = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  return jsonResult;
}

- (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:
    (const facebook::react::ObjCTurboModule::InitParams &)params
 {
    return std::make_shared<facebook::react::NativeVertcSpecJSI>(params);
 }

@end
