#import "RNZoomVideoSdkBroadcastStreamingViewer.h"
#import "RCTConvert+RNZoomVideoSdk.h"

@implementation RNZoomVideoSdkBroadcastStreamingViewer

- (ZoomVideoSDKBroadcastStreamingViewerHelper *)getViewer
{
    ZoomVideoSDKBroadcastStreamingViewerHelper* viewer = nil;
    @try {
        viewer = [[ZoomVideoSDK shareInstance] getBroadcastStreamingViewerHelper];
        if (viewer == nil) {
            NSException *e = [NSException exceptionWithName:@"NoBroadcastStreamingViewerFound"
                                                     reason:@"No Broadcast Streaming Viewer Found"
                                                   userInfo:nil];
            @throw e;
        }
    } @catch(NSException *e) {
        NSLog(@"%@ - %@", e.name, e.reason);
    }
    return viewer;
}

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(joinStreaming:(NSDictionary *)ctx
                  resolver:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ZoomVideoSDKBroadcastStreamingViewerHelper *viewer = [self getViewer];
        if (viewer == nil) {
            resolve([NSNull null]);
            return;
        }
        ZoomVideoSDKStreamingJoinContext *joinContext = [[ZoomVideoSDKStreamingJoinContext alloc] init];
        joinContext.token = ctx[@"token"];
        joinContext.channelID = ctx[@"channelID"];
        resolve([[RCTConvert ZoomVideoSDKErrorValuesReversed] objectForKey:@([viewer joinStreaming:joinContext])]);
    });
}

RCT_EXPORT_METHOD(leaveStreaming:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ZoomVideoSDKBroadcastStreamingViewerHelper *viewer = [self getViewer];
        if (viewer == nil) {
            resolve([NSNull null]);
            return;
        }
        resolve([[RCTConvert ZoomVideoSDKErrorValuesReversed] objectForKey:@([viewer leaveStreaming])]);
    });
}

RCT_EXPORT_METHOD(getStreamingJoinStatus:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    ZoomVideoSDKBroadcastStreamingViewerHelper *viewer = [self getViewer];
    if (viewer == nil) {
        resolve([NSNull null]);
        return;
    }
    resolve([[RCTConvert ZoomVideoSDKStreamingJoinStatusValuesReversed] objectForKey:@([viewer getStreamingJoinStatus])]);
}

@end
