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

@implementation RNZoomVideoSdkBroadcastStreamingHelper

- (ZoomVideoSDKBroadcastStreamingHelper *)getHelper
{
    ZoomVideoSDKBroadcastStreamingHelper* helper = nil;
    @try {
        helper = [[ZoomVideoSDK shareInstance] getBroadcastStreamingHelper];
        if (helper == nil) {
            NSException *e = [NSException exceptionWithName:@"NoBroadcastStreamingHelperFound"
                                                     reason:@"No Broadcast Streaming Helper Found"
                                                   userInfo:nil];
            @throw e;
        }
    } @catch(NSException *e) {
        NSLog(@"%@ - %@", e.name, e.reason);
    }
    return helper;
}

RCT_EXPORT_MODULE()

RCT_EXPORT_METHOD(isBroadcastStreamingSupported:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    ZoomVideoSDKBroadcastStreamingHelper *helper = [self getHelper];
    resolve(@(helper != nil && [helper isBroadcastStreamingSupported]));
}

RCT_EXPORT_METHOD(canStartBroadcast:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    ZoomVideoSDKBroadcastStreamingHelper *helper = [self getHelper];
    resolve(@(helper != nil && [helper canStartBroadcast]));
}

RCT_EXPORT_METHOD(startBroadcast:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ZoomVideoSDKBroadcastStreamingHelper *helper = [self getHelper];
        if (helper == nil) {
            resolve([NSNull null]);
            return;
        }
        resolve([[RCTConvert ZoomVideoSDKErrorValuesReversed] objectForKey:@([helper startBroadcast])]);
    });
}

RCT_EXPORT_METHOD(stopBroadcast:(NSString *)channelID
                  resolver:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ZoomVideoSDKBroadcastStreamingHelper *helper = [self getHelper];
        if (helper == nil) {
            resolve([NSNull null]);
            return;
        }
        resolve([[RCTConvert ZoomVideoSDKErrorValuesReversed] objectForKey:@([helper stopBroadcast:channelID])]);
    });
}

RCT_EXPORT_METHOD(getBroadcastStatus:(NSString *)channelID
                  resolver:(RCTPromiseResolveBlock)resolve
                  withRejecter:(RCTPromiseRejectBlock)reject)
{
    ZoomVideoSDKBroadcastStreamingHelper *helper = [self getHelper];
    if (helper == nil) {
        resolve([NSNull null]);
        return;
    }
    resolve([[RCTConvert ZoomVideoSDKErrorValuesReversed] objectForKey:@([helper getBroadcastStatus:channelID])]);
}

@end
