//
//  FloatingWindow.m
//  AIIM
//
//  Created by gan on 2025/7/9.
//

#import <Foundation/Foundation.h>
#import "FloatJSWindow.h"
#import "APPLocker.h"
#import "GDBManager.h"
#import "UserNetApi.h"
#import "GWebSocket.h"

@interface FloatJSWindow ()<JitsiMeetViewDelegate>
@property (nonatomic,strong) JitsiMeetView *jitsiView;
@property (nonatomic, strong) JitsiMeetConferenceOptions * currentOptions;
@property (nonatomic, assign) NSUInteger reconnectAttempt;
@property (nonatomic, assign) BOOL isInConference;
@property (nonatomic, assign) BOOL isReconnecting;
@property (nonatomic) BOOL isSpeacker;
@property (nonatomic) BOOL isjoin;
@property (nonatomic) BOOL floadViewState;
@property (nonatomic,strong) AVAudioPlayer * audioPlayer;
@property (nonatomic) NSInteger startTime;

@end

@implementation FloatJSWindow {

}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        self.isfirstShow=YES;
        UIImageView * bgImageView = [[UIImageView alloc] initWithImage:kImageMake(@"loginBG")];
        [self addSubview:bgImageView];
        [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.bottom.mas_equalTo(0);
        }];
        _jitsiView = [(JitsiMeetView*)[UIView alloc] initWithFrame:frame];
        [self addSubview:_jitsiView];
        _jitsiView.delegate = self;
    }
    return self;
}

- (void)show {
    self.hidden = NO;
   
}

- (void)hide {
    self.hidden = YES;
}



#pragma mark JitsiMeetView act

-(void)initjsView{
    // Attach this controller as the delegate.

    JitsiMeetConferenceOptions *options=nil;
    if(self.isCaller){
        // create the room.JitsiMeetConferenceOptions
        options = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
            builder.serverURL = [NSURL URLWithString:JitsiMeetSV];
            builder.room = self.room;
            builder.audioOnly = self.audioOnly;
            [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"pip.enabled" withBoolean:YES];
            [builder setFeatureFlag:@"ios.screensharing.enabled" withBoolean:YES];
            [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
            [builder setFeatureFlag:@"prejoinpage.enabled" withBoolean:NO];
            [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
            [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
            [builder setConfigOverride:@"enableNetworkMonitor" withBoolean:YES];
            [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
            
//            //界面优化 - 隐藏不必要的会议功能
//            [builder setFeatureFlag:@"live-streaming.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"recording.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"kick-out.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"security-options.enabled" withBoolean:NO];
//
//            // 界面简化 - 更适合一对一场景
//            [builder setFeatureFlag:@"toolbox.alwaysVisible" withBoolean:NO];
//            [builder setFeatureFlag:@"filmstrip.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"thumbnail.enabled" withBoolean:NO];
//            [builder setFeatureFlag:@"disableRtx" withBoolean:YES];// 一对一不需要RTX
//            [builder setFeatureFlag:@"disableNS" withBoolean:YES];     // 降噪可关闭
//
//            [builder setFeatureFlag:@"ios.audio-handler" withBoolean:NO];
            
            [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
        }];
    }
    else{
        // Join the room.
        options
            = [JitsiMeetConferenceOptions fromBuilder:^(JitsiMeetConferenceOptionsBuilder *builder) {
                builder.room = self.room;
                builder.audioOnly = self.audioOnly;
                [builder setFeatureFlag:@"welcomepage.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"pip.enabled" withBoolean:YES];
                [builder setFeatureFlag:@"ios.screensharing.enabled" withBoolean:YES];
                [builder setFeatureFlag:@"chat.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"invite.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"add-people.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"video-share.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"call-integration.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"startWithAudioMuted" withBoolean:NO];
                [builder setFeatureFlag:@"prejoinpage.enabled" withBoolean:NO];
                [builder setFeatureFlag:@"reconnect.enabled" withBoolean:YES];
                [builder setConfigOverride:@"iceTransportPolicy" withValue:@"relay"];
                [builder setConfigOverride:@"enableNetworkMonitor" withBoolean:YES];
                [builder setConfigOverride:@"toolbarButtons" withArray:@[@"microphone",@"camera"]];
            }];
    }
    self.currentOptions = options;
    
    
}

- (void)conferenceWillJoin:(NSDictionary *)data {
    NSLog(@"About to join conference---- %@", self.room);
    self.isInConference = NO;
    if (self.isCaller) {
//        [self sendCall];
    }
    else{
        NSLog(@"self.audioPlayer-----------");
//        [self.audioPlayer play];
    }
    
    if (!self.audioOnly) {
//        [self setupPictureInPicture];
    }
    
//    [[AudioRouteManager sharedManager] setOutputToEarpiece];
}

- (void)conferenceJoined:(NSDictionary *)data {
    _reconnectAttempt = 0;
    _isInConference = YES;
    NSLog(@"Conference %@ joined----11222-------", self.room);
    if(!self.isCaller){
        [self.audioPlayer stop];
    }
}

- (void)conferenceTerminated:(NSDictionary *)data {
    NSLog(@"conferenceTerminated----------------------");
    _isInConference = NO;
    
    NSString *error = data[@"error"];
    if (error) {
        if ([error isEqualToString:@"connection.otherError"]) {
//            [self reconnectConference];
        } else {
            NSLog(@"%@",error);
        }
    }
}

- (void)readyToClose:(NSDictionary *)data {
    NSLog(@"readyToClose-----:%@",data);
    
    if (_isReconnecting) {
        return;
    }
    
//    [self endCall];
    [_jitsiView closeChat];
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)customButtonPressed:(NSDictionary *)data {
    NSLog(@"---------Custom button pressed %@", data);
}

-(void)participantJoined:(NSDictionary *)data{
    NSLog(@"------1-------participantJoined");
    if(_startTime==0){
        NSDate *now = [NSDate date];
        NSTimeInterval trt = [now timeIntervalSince1970];
        _startTime = trt*1000;
    }
    [self.audioPlayer stop];
    // 使用GCD创建一个在3秒后执行的定时器
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"Timer fired using GCD!");
        [self inispeacker];
    });
    
}

- (void)participantLeft:(NSDictionary *)data{
    NSLog(@"participantLeft:%@",data);
    //p2p 一方退出，就挂掉
//    [self endCall];
    [_jitsiView closeChat];
//    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)inispeacker{
    if(self.audioOnly){
        _isSpeacker=NO;
        [_jitsiView changeAudioSession:NO];
    }
    else{
        _isSpeacker=YES;
        [_jitsiView changeAudioSession:YES];
    }
}


@end
