// Copyright © 2022 BytePlusRTC All rights reserved.
// SPDX-License-Identifier: MIT

//
//  VertcModule.m
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "VolcApiEngine/VolcEventObserver.h"
#import "VertcApiEngine.h"
#import "RTCHeader.h"

#import "VertcModule.h"

#define EVENT_NAME @"VertcModule:onEvent"

@interface RTCHandler () <EventObserver>

@end

static RCTVertcModule *instance = nil;

@implementation RCTVertcModule
{
  bool hasListeners;
}

+ (instancetype)shareInstance {
    return instance;
}

+ (BOOL)requiresMainQueueSetup {
    return YES;
}

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

- (instancetype)init {
    self = [super init];
    if (self != nil) {
        self.volcApiEngine = nil;
        instance = self;
    }
    return instance;
}

- (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();

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(newApiEngine)
{
  if (self.volcApiEngine == nil) {
    self.volcApiEngine = [[VolcApiEngine alloc] init];
    [self.volcApiEngine setObserver:self];
    [VertcApiEngine.sharedInstance setApiEngine:[self volcApiEngine]];
  }
  return nil;
}

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(callApiSync:(nonnull NSDictionary *) args)
{
  [self newApiEngine];
  return [instance.volcApiEngine callApi:args];
}

RCT_EXPORT_METHOD(callApi:(nonnull NSDictionary *)args callback:(RCTResponseSenderBlock) callback)
{
  [self newApiEngine];
  dispatch_async(dispatch_get_main_queue(), ^{
    id _val = [self.volcApiEngine callApi:args];
    callback(@[_val]);
  });
}

RCT_EXPORT_METHOD(test)
{
    // test something
    ByteRTCVideo *video = [ByteRTCVideo createRTCVideo:@"" delegate:nil parameters:nil];
//    ByteRTCRoom *room = [video createRTCRoom:@""];
//    [video setLocalVideoCanvas: withCanvas:<#(ByteRTCVideoCanvas * _Nullable)#>:nil];
//    [room unpublishStream:(ByteRTCMediaStreamType)]
}

@end
