//
//  RTCSiglePageCallView.m
//  rtc_sdk_ios
//
//  Created by v_liyingna on 11/30/22.
//  Copyright © 2022 Sun,Jian(ACU-T102). All rights reserved.
//

#import "RTCSiglePageCallView.h"
#import <AVFoundation/AVFoundation.h>
#import "BDCloudRTCBaseDefine.pch"

@implementation RTCsubviewInfo

- (instancetype)initWithParams:(BOOL)local uid:(NSString*)userId view:(UIView*)subView size:(CGSize)videoResolution {
    if (self = [super init]) {
        self.userId = userId;
        self.isLocal = local;
        self.showView = subView;
        self.videoResolution = videoResolution;
    }
    return self;
}

@end

@interface RTCSiglePageCallView ()
@property (nonatomic, strong) NSMutableDictionary *shownVideoViews;
@property (nonatomic, strong) NSMutableDictionary *noShownVideoViews;
@property (nonatomic, assign) BOOL isWatch;
@property (nonatomic, assign) NSInteger currentStyle;
@property (nonatomic, strong) UIButton *style1;
@property (nonatomic, strong) UIButton *style2;
@property (nonatomic, strong) UIButton *style3;

@end

@implementation RTCSiglePageCallView
@synthesize  remoteUids = _remoteUids;
@synthesize  allAddedUids = _allAddedUids;

- (instancetype)initWithFrame:(CGRect)frame isWatch:(BOOL)isWatch {
    
    if (self = [super initWithFrame:frame]) {
        _shownVideoViews = [NSMutableDictionary dictionary];
        _noShownVideoViews = [NSMutableDictionary dictionary];
        _isWatch = isWatch;
        _currentStyle = 0;
    }
    self.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|
                            UIViewAutoresizingFlexibleWidth|
                            UIViewAutoresizingFlexibleRightMargin|
                            UIViewAutoresizingFlexibleTopMargin|
                            UIViewAutoresizingFlexibleHeight|
                            UIViewAutoresizingFlexibleBottomMargin;
    return self;
}

- (NSMutableArray *)remoteUids {
    if(!_remoteUids) {
        _remoteUids = [NSMutableArray array];
    }
    return _remoteUids;
}

- (NSMutableArray *)allAddedUids {
    if(!_allAddedUids) {
        _allAddedUids = [NSMutableArray array];
    }
    return _allAddedUids;
}

- (void)addRTCsubView:(NSString *)uId local:(BOOL)isLocal view:(UIView*)subview size:(CGSize)videoRelution show:(BOOL)isShow {
    
    NSLog(@"vocs addRTCsubView: uId:%@, show:%@, self : %@,  view : %@, size : %f, %f", uId, (isShow ? @"yes" : @"no"), self, subview, videoRelution.width, videoRelution.height);
    if (subview) {
        RTCsubviewInfo* rtcSubviewInfo = [[RTCsubviewInfo alloc] initWithParams:isLocal uid:uId view:subview size:videoRelution];
        if (isShow) {
            [_shownVideoViews setObject:rtcSubviewInfo forKey:uId];
            [self addSubview:subview];
            [self setNeedsLayout];
        } else {
            [_noShownVideoViews setObject:rtcSubviewInfo forKey:uId];
        }
        
    }
    if (!isLocal && isShow) {
        [self.remoteUids addObject:uId];
        if (![self.allAddedUids containsObject:uId]) {
            [self.allAddedUids addObject:uId];
        }
    }
}

- (void)addToolsView {
    if (self.style1 && self.style2 && self.style3) {
        return;
    }
    
    self.style1 = [self createBtn:@"style1"];
    self.style2 = [self createBtn:@"style2"];
    self.style3 = [self createBtn:@"style3"];

    [self addSubview:self.style1];
    [self addSubview:self.style2];
    [self addSubview:self.style3];

    int xpos = SCREEN_WIDTH*100*kLayoutWidthScale;
    int ypos = self.bounds.size.height - 60;
    int width = SCREEN_WIDTH*160*kLayoutWidthScale;
    
    self.style1.frame = CGRectMake(xpos, ypos, width, 40);
    xpos += (width + 20);
    self.style2.frame = CGRectMake(xpos, ypos, width, 40);
    xpos += (width + 20);
    self.style3.frame = CGRectMake(xpos, ypos, width, 40);
}

- (void)onStyleChanged:(id)btn {
    if ([self.remoteUids count] == 0) {
        return;
    }
    
    if (btn == self.style1) {
        NSLog(@"onStyleChanged style1");
        self.currentStyle = 1;
        [self updateRemoteVideoViewSize];
    } else if (btn == self.style2) {
        NSLog(@"onStyleChanged style2");
        self.currentStyle = 2;
        [self updateRemoteVideoViewSize];
    } else if (btn == self.style3) {
        NSLog(@"onStyleChanged style3");
        self.currentStyle = 3;
        [self updateRemoteVideoViewSize];
    }
}

- (void)updateRemoteVideoViewSize {
    NSMutableArray *videoViews = [NSMutableArray array];
    NSMutableArray *tempVideoViews = [NSMutableArray array];
//    [videoViews addObjectsFromArray:[_shownVideoViews allValues]];
    NSArray *array = [_shownVideoViews allValues];
    for (int i = 0; i < array.count; i ++) {
        RTCsubviewInfo *tempInfo = array[i];
        if (tempInfo.isLocal) {
            [videoViews addObject:tempInfo];
        } else {
            [tempVideoViews addObject:tempInfo];
        }
    }
    [videoViews addObjectsFromArray:tempVideoViews];
    [self layoutSubviews1V1Watch:videoViews];
}

- (UIButton *)createBtn:(NSString *)name {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.backgroundColor = [UIColor magentaColor];
    btn.titleLabel.adjustsFontSizeToFitWidth = YES;
    [btn setTitle:name forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(onStyleChanged:) forControlEvents:UIControlEventTouchUpInside];
    return btn;
}


- (void)removeRTCsubView:(NSString *)uId {
    if ([_noShownVideoViews.allKeys containsObject:uId]) {
        [_noShownVideoViews removeObjectForKey:uId];
        return;
    }
    RTCsubviewInfo* subviewInfo = [_shownVideoViews objectForKey:uId];
    if (subviewInfo.showView != nil) {
        [subviewInfo.showView removeFromSuperview];
        subviewInfo.showView = nil;
        [_shownVideoViews removeObjectForKey:uId];
        [_remoteUids removeObject:uId];
        if (_noShownVideoViews.allKeys.count > 0) {
            NSArray *noShowArray = _noShownVideoViews.allValues;
            RTCsubviewInfo *tempInfo = noShowArray.firstObject;
            [self addSubview:tempInfo.showView];
            [_shownVideoViews setObject:tempInfo forKey:tempInfo.userId];
            [self.remoteUids addObject:tempInfo.userId];
            [_noShownVideoViews removeObjectForKey:tempInfo.userId];
        }
        [self setNeedsLayout];
    }
}

/** 手表1v1 场景 */
- (void)layoutSubviews1V1Watch:(NSMutableArray *) videoViews{
    int ypos = 0;
    if (((RTCsubviewInfo *)videoViews[0]).isLocal) {
//        int width = self.bounds.size.width/3;
        int width = 160;
        int height = 160;
        ypos  = height;

        CGRect rectMid = CGRectMake(self.bounds.size.width-width-10, 0, width, height);
        ((RTCsubviewInfo*)videoViews[0]).showView.frame = rectMid;
        [self bringSubviewToFront:((RTCsubviewInfo*)videoViews[0]).showView];
    } else {
        CGRect rectMid = CGRectMake(0, self.bounds.size.height/4, self.bounds.size.width/2, self.bounds.size.height/2);
        ((RTCsubviewInfo *)videoViews[0]).showView.frame = [self tranctOriginRectToRealRect:((RTCsubviewInfo *)videoViews[0]).videoResolution physicRect:rectMid];
    }

    if (((RTCsubviewInfo*)videoViews[1]).isLocal) {
        CGRect rectMidOther = CGRectMake(self.bounds.size.width*2/3, 0, self.bounds.size.width/3, self.bounds.size.height/3);
        ((RTCsubviewInfo*)videoViews[1]).showView.frame = rectMidOther;
    } else {
        int width = SCREEN_WIDTH*600*kLayoutWidthScale;
        int height = SCREEN_WIDTH*600*kLayoutWidthScale;
        if (self.currentStyle == 1) {
            /** 530*432px */
            width = 176;
            height = 144;
        } else if (self.currentStyle == 2) {
            /** 530*530 */
            width = 176;
            height = 176;
        } else if (self.currentStyle == 3) {
            /** 700*700 */
            width = 233;
            height = 233;
        }
        ypos += 10;
        int xpos = (SCREEN_WIDTH*1242*kLayoutWidthScale-width)/2;
        
        CGRect rectMidOther = CGRectMake(xpos, ypos, width, height);
        ((RTCsubviewInfo *)videoViews[1]).showView.frame = [self tranctOriginRectToRealRect:((RTCsubviewInfo *)videoViews[1]).videoResolution physicRect:rectMidOther];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.isWatch) {
        [self addToolsView];
    }
 
    NSMutableArray *videoViews = [NSMutableArray array];
    NSMutableArray *tempVideoViews = [NSMutableArray array];
//    [videoViews addObjectsFromArray:[_shownVideoViews allValues]];
    NSArray *array = [_shownVideoViews allValues];
    for (int i = 0; i < array.count; i ++) {
        RTCsubviewInfo *tempInfo = array[i];
        if (tempInfo.isLocal) {
            [videoViews addObject:tempInfo];
        } else {
            [tempVideoViews addObject:tempInfo];
        }
    }
    [videoViews addObjectsFromArray:tempVideoViews];
    
    if (videoViews.count == 1) {
        if(((RTCsubviewInfo *)videoViews[0]).isLocal) {
            CGRect rectMid = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
            ((RTCsubviewInfo *)videoViews[0]).showView.frame = rectMid;
        } else {
            CGRect rectMid = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
            ((RTCsubviewInfo *)videoViews[0]).showView.frame = [self tranctOriginRectToRealRect:((RTCsubviewInfo *)videoViews[0]).videoResolution physicRect:rectMid];
        }
        
    } else if (videoViews.count == 2) {
        if (self.isWatch) {
            [self layoutSubviews1V1Watch:videoViews];
            return;
        }
        if (((RTCsubviewInfo *)videoViews[0]).isLocal) {
            CGRect rectMid = CGRectMake(self.bounds.size.width*2/3, 0, self.bounds.size.width/3, self.bounds.size.height/3);
            ((RTCsubviewInfo*)videoViews[0]).showView.frame = rectMid;
            [self bringSubviewToFront:((RTCsubviewInfo*)videoViews[0]).showView];
        } else {
            CGRect rectMid = CGRectMake(0, self.bounds.size.height/4, self.bounds.size.width/2, self.bounds.size.height/2);
            ((RTCsubviewInfo *)videoViews[0]).showView.frame = [self tranctOriginRectToRealRect:((RTCsubviewInfo *)videoViews[0]).videoResolution physicRect:rectMid];
        }

        if (((RTCsubviewInfo*)videoViews[1]).isLocal) {
            CGRect rectMidOther = CGRectMake(self.bounds.size.width*2/3, 0, self.bounds.size.width/3, self.bounds.size.height/3);
            ((RTCsubviewInfo*)videoViews[1]).showView.frame = rectMidOther;
        } else {
            CGRect rectMidOther = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);
            ((RTCsubviewInfo *)videoViews[1]).showView.frame = [self tranctOriginRectToRealRect:((RTCsubviewInfo *)videoViews[1]).videoResolution physicRect:rectMidOther];
        }
    }
    else if (videoViews.count > 2 && videoViews.count <= 4) {
        for (int i=0; i < videoViews.count; i++) {
            RTCsubviewInfo *tempInfo = videoViews[i];
            CGRect rectMidOther = CGRectMake(i%2 * self.bounds.size.width / 2.0, i/2 * self.bounds.size.height / 2.0 , self.bounds.size.width / 2.0, self.bounds.size.height / 2.0);

            tempInfo.showView.frame = [self tranctOriginRectToRealRect:tempInfo.videoResolution physicRect:rectMidOther];
        }
    }
    else if (videoViews.count > 4 ) {
        for (int i=0; i < (videoViews.count > BDSiglePageNumber ? BDSiglePageNumber : videoViews.count); i++) {
            RTCsubviewInfo *tempInfo = videoViews[i];
            CGRect rectMidOther = CGRectMake(i%3 * self.bounds.size.width / 3.0, i/3 * self.bounds.size.width / 3.0 , self.bounds.size.width / 3.0, self.bounds.size.width / 3.0);
            tempInfo.showView.frame = [self tranctOriginRectToRealRect:tempInfo.videoResolution physicRect:rectMidOther];
        }
    }
}

- (CGRect)tranctOriginRectToRealRect:(CGSize)videoResolution physicRect:(CGRect)rectMidOther  {
    if (videoResolution.width > 0 && videoResolution.height > 0) {
        CGRect videoViewFrame = AVMakeRectWithAspectRatioInsideRect(videoResolution, rectMidOther);
        return videoViewFrame;
    } else {
        return rectMidOther;
    }
}

@end
