//
//  ERTCPlayerViewManager.m
//  ERTCDemo
//
//  Created by wangjinlong23 on 2022/5/13.
//

#import "ERTCPlayerViewManager.h"
#import "EZConfGlobalConfig.h"
#import "ERTCGenerateTestRTCToken.h"

@interface ERTCPlayerViewManager ()
@property (nonatomic, copy) void(^enterRoomBlock)(NSError *error);

@end

@implementation ERTCPlayerViewManager

+ (instancetype)sharedInstance {
    static ERTCPlayerViewManager *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [ERTCPlayerViewManager new];
    });
    
    return _sharedInstance;
}

- (void)enterRoomWithRoomId:(NSString *)roomId userId:(NSString *)userId  completion:(void (^)(NSError *error))completion {
    self.enterRoomBlock = completion;
    @WeakObj(self);
    void(^joinBlock)(NSString *token) = ^(NSString *token) {
        @StrongObj(self);
        ERTCLog(@"加入房间---调用enterRoom");
        ERTCParam *param = [ERTCParam new];
        param.roomId = roomId;
        param.userId = userId;
        param.token = token;
        [self.engine enterRoom:param withScene:ERTCAppScene_VideoCall];
    };
    [self fetchNewTokenWithRoomId:roomId userId:userId finishBlock:^(NSString *token) {
        dispatch_async(dispatch_get_main_queue(), ^{
            joinBlock(token);
        });
    }];
}

- (void)creatConfig:(void(^)(NSError *error))completion {
    [[ERTCLog sharedInstance] setERTCDebugLog:NO];
    ERTCEngineConfig *config = [ERTCEngineConfig new];
    config.appID = g_APPID;
    config.platformAddress = g_platformAddress;
    config.lineId = g_LineID;
    @WeakObj(self);
    [ERTCEngine createWithConfig:config instanceBlock:^(ERTCEngine * _Nullable instance, NSError * _Nullable error) {
        @StrongObj(self);
        if (instance) {
            self.engine = instance;
            [self.engine setQualityInterval:[EZConfGlobalConfig sharedInstance].qualityInterval];
            [self.engine setHardDecodePriority:[EZConfGlobalConfig sharedInstance].hardDecodePriority];
            [self.engine setVideoEncoderParam:[EZConfGlobalConfig sharedInstance].bigVideoEncParam];
            [self.engine enableLocalSmallVideo:YES withQuality:[EZConfGlobalConfig sharedInstance].smallVideoEncParam];
            if (completion != nil) {
                completion(nil);
            }
            
        } else {
            if (completion != nil) {
                completion(error);
            }
        }
    }];
}

- (void)fetchNewTokenWithRoomId:(NSString *)roomId userId:(NSString *)userId  finishBlock:(void (^)(NSString *token))finishBlock {
    finishBlock(g_Token);
}

- (void)exitRoom {
    if (self.engine) {
        [self.engine stopScreenShare];
        [self.engine exitRoom];
        self.engine.delegate = nil;
        self.engine = nil;
        [ERTCEngine destroySharedIntance];
    }
}

@end
