//
//  SMTestIPCPlayerContainer.m
//  SM_LivePlayBack_BusinessCmp
//
//  Created by Lee on 2022/10/9.
//

#import "SMTestIPCPlayerContainer.h"
#import "Masonry.h"

typedef struct {
    BOOL didScrollFromIndexToNewIndex;                         ///< 是否是真的手动滑动到上/下一个
    BOOL manualResetContentSize;                               ///< 标记旋转的时候手动重置ScrollView的ContentSize
    NSUInteger currentIndex;                                   ///< 当前滑动到的的index
    SMTestIPCScrollStare scrollStare;                          ///< IPC Player Container的滑动状态
} SMTestIpcScrollFlags;

BOOL SMTestIPCScrollIsValidIndex(NSInteger index, NSInteger count) {
    if (index >= 0 && index < count) {
        return YES;
    }
    return NO;
}

BOOL SMTestIPCScrollByStep(NSInteger toIndex, NSInteger currentIndex, NSInteger count) {
    NSInteger preIndex = currentIndex - 1;
    NSInteger nextIndex = currentIndex + 1;
    if (SMTestIPCScrollIsValidIndex(preIndex, count) && preIndex == toIndex) {
        return YES;
    }
    if (SMTestIPCScrollIsValidIndex(nextIndex, count) && nextIndex == toIndex) {
        return YES;
    }
    return NO;
}

@interface SMTestIPCPlayerContainer ()<UIScrollViewDelegate, UIGestureRecognizerDelegate> {
    SMTestIpcScrollFlags _scrollFlags;
    BOOL _isLandScape;
}
@property (nonatomic, weak, readwrite) id<SMTestIPCPlayerContainerDelegate> delegate;
@property (nonatomic, strong, readwrite) SMTestScrollView *scrollView;
@property (nonatomic, assign) NSInteger initialIndex;
@property (nonatomic, assign) NSInteger videoCount;

@end

@implementation SMTestIPCPlayerContainer

#pragma mark - Life Cycle

- (instancetype)initWithIndex:(NSInteger)index
                   videoCount:(NSInteger)videoCount
                     delegate:(id<SMTestIPCPlayerContainerDelegate>)delegate {
    self = [super init];
    if (self) {
        self.initialIndex = index;
        _scrollFlags.didScrollFromIndexToNewIndex = NO;
        _scrollFlags.manualResetContentSize = NO;
        _scrollFlags.currentIndex = index;
        _scrollFlags.scrollStare = SMTestIPCScrollStareNormal;
        self.videoCount = videoCount;
        self.delegate = delegate;
        [self setup];
    }
    return self;
}

- (void)setup {
    self.backgroundColor = UIColor.blackColor;
    [self addSubview:self.scrollView];
    [self.scrollView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    for (int i = 0; i < self.videoCount; i++) {
        [self.scrollView containerAppendSubview:[self createPlayerViewAtIndex:i]];
    }
    [self.scrollView containerLayoutSubview];
}

- (UIView *)createPlayerViewAtIndex:(NSUInteger)index {
    UIView *playView = [[UIView alloc] init];
    if (index % 2 == 0) {
        playView.backgroundColor = UIColor.blueColor;
    } else {
        playView.backgroundColor = UIColor.redColor;
    }
    
    return playView;
}


#pragma mark - Scroll To InitialIndex

- (void)scrollToInitialIndex {
    [self.scrollView setContentOffset:CGPointMake(MAINSCREEN_WIDTH * self.initialIndex, 0)];
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return !_isLandScape;
}

#pragma mark - ScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat pageWidth = self.scrollView.itemSize.width;
    NSInteger toIndex = (scrollView.contentOffset.x + pageWidth  * 0.5) / pageWidth;
    CGFloat offsetX = fabs(scrollView.contentOffset.x - toIndex * pageWidth);
    if (_scrollFlags.manualResetContentSize) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(playerContainerDidCancleScrolling:)] && offsetX <= 0.5) {
        _scrollFlags.scrollStare = SMTestIPCScrollStareCancelled;
        [self.delegate playerContainerDidCancleScrolling:self];
    }
    if ([self.delegate respondsToSelector:@selector(playerContainer:willScrollFromIndex:)]) {
        if (offsetX < 20) {
            _scrollFlags.scrollStare = SMTestIPCScrollStareBegan;
        } else {
            _scrollFlags.scrollStare = SMTestIPCScrollStareChanged;
            [self.delegate playerContainer:self willScrollFromIndex:_scrollFlags.currentIndex];
        }
    }
    if ([self.delegate respondsToSelector:@selector(playerContainer:didScrollFromIndex:toIndex:)] && SMTestIPCScrollByStep(toIndex, _scrollFlags.currentIndex, self.videoCount)) {
        [self.delegate playerContainer:self didScrollFromIndex:_scrollFlags.currentIndex toIndex:toIndex];
        _scrollFlags.currentIndex = toIndex;
        _scrollFlags.didScrollFromIndexToNewIndex = YES;
        _scrollFlags.scrollStare = SMTestIPCScrollStareEnded;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([self.delegate respondsToSelector:@selector(playerContainerDidEndScrolling:)] && _scrollFlags.didScrollFromIndexToNewIndex) {
        [self.delegate playerContainerDidEndScrolling:self];
        _scrollFlags.didScrollFromIndexToNewIndex = NO;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (decelerate) {
        return;
    }
    if ([self.delegate respondsToSelector:@selector(playerContainerDidEndScrolling:)] && _scrollFlags.didScrollFromIndexToNewIndex) {
        [self.delegate playerContainerDidEndScrolling:self];
        _scrollFlags.didScrollFromIndexToNewIndex = NO;
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if ([self.delegate respondsToSelector:@selector(playerContainerDidEndScrolling:)] && _scrollFlags.didScrollFromIndexToNewIndex) {
        [self.delegate playerContainerDidEndScrolling:self];
        _scrollFlags.didScrollFromIndexToNewIndex = NO;
    }
}

#pragma mark - Getters

- (UIView *)playView {
    NSArray *subviews = self.scrollView.container.subviews;
    UIView *playerView = subviews[_scrollFlags.currentIndex];
    return playerView;
}

- (NSInteger)currentIndex {
    return _scrollFlags.currentIndex;
}

- (BOOL)isScrolling {
    return _scrollFlags.scrollStare;
}

- (SMTestScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[SMTestScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
        _scrollView.bounces = NO;
        _scrollView.alwaysBounceHorizontal = NO;
        _scrollView.pagingEnabled = YES;
        _scrollView.layout = SMScrollViewLayoutHorizontal;
        _scrollView.itemSize = CGSizeMake(MAINSCREEN_WIDTH, 230);
        _scrollView.innerSpace = 0;
        _scrollView.needHandlePopGestureConflict = YES;
        _scrollView.canPopBackWhenNotInFirstPageView = YES;
    }
    return _scrollView;
}

@end
