//
//  GMInfinitelView.m
//  
//
//  Created by wangyang on 10/12/15.
//  Copyright (c) 2015年 Wanmeichuangyi. All rights reserved.
//

#import "GMInfiniteScrollView.h"
#import "GMImageView.h"

#define IMAGE_TAG       1000

@implementation GMInfiniteScrollView

- (void)setup{
    [super setup];
    // 显示的是图片数组里的第一张图片
    // 和数组是+1关系
    _currentPage = 0;

    _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    _scrollView.backgroundColor = UIColor.whiteColor;
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.scrollsToTop = NO;
    [self addSubview:_scrollView];
    
    self.pageControl = [UIPageControl new];
    self.pageControl.currentPage = 0;
    self.pageControl.hidesForSinglePage = YES;
    [self addSubview:self.pageControl];

    self.imageContentMode = UIViewContentModeScaleAspectFill;

    // 在应用后台时关闭播放,前台时开启
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopRolling) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startRolling) name:UIApplicationWillEnterForegroundNotification object:nil];
}


- (void)layoutSubviews{
    [super layoutSubviews];
    
    self.pageControl.frame = CGRectMake(0, self.frame.size.height-15, self.frame.size.width, 15);
    self.pageControl.center = CGPointMake(self.frame.size.width / 2, self.pageControl.center.y);
}


- (void)dealloc
{
    self.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
}
#pragma mark - Setter
- (void)setImageArray:(NSArray *)imageArray{

    _imageArray = imageArray;

    if(_imageArray.count == 0) {
        return;
    }

    // 如果只有一个,不允许滑动
    _scrollView.scrollEnabled = _imageArray.count == 1 ? NO : YES;

    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * 3,
                                         _scrollView.frame.size.height);
    for (NSInteger i = 0; i < 3; i++){
        CGRect frame = CGRectOffset(_scrollView.bounds, _scrollView.frame.size.width * i, 0);
        GMImageView *imageView = [[GMImageView alloc] initWithFrame:frame];
        imageView.userInteractionEnabled = YES;
        imageView.clipsToBounds = YES;
        imageView.contentMode = self.imageContentMode;
        imageView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        imageView.tag = i + IMAGE_TAG;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [imageView addGestureRecognizer:singleTap];
        [_scrollView addSubview:imageView];
    }
    
    self.pageControl.numberOfPages = self.self.imageArray.count;

    _currentPage = 1;
    [self refreshScrollView];
}

#pragma mark - Custom Method
- (void)refreshScrollView{
    NSArray *imageArray = [self getDisplayImagesWithPageIndex:_currentPage];
    for (NSInteger i = 0; i < 3; i++){
        GMImageView *imageView = (GMImageView *)[_scrollView viewWithTag:i + IMAGE_TAG];
        NSString *url = imageArray[i];
        [imageView setImageWithUrlString:url placeHolder:nil];
    }
    
    // 水平滚动
    _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);
    self.pageControl.currentPage = _currentPage-1;
}

- (NSArray *)getDisplayImagesWithPageIndex:(NSInteger)page{
    NSInteger pre = [self getPageIndex:_currentPage-1];
    NSInteger last = [self getPageIndex:_currentPage+1];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:0];
    
    [images addObject:[self.imageArray objectAtIndex:pre-1]];
    [images addObject:[self.imageArray objectAtIndex:_currentPage-1]];
    [images addObject:[self.imageArray objectAtIndex:last-1]];
    
    return images;
}

- (NSInteger)getPageIndex:(NSInteger)index{
    // value=1为第一张,value = 0为前面一张
    if (index == 0)
    {
        index = self.imageArray.count;
    }
    
    if (index == self.imageArray.count + 1)
    {
        index = 1;
    }
    
    return index;
}


#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger x = scrollView.contentOffset.x;
    
    //取消已加入的延迟线程
    if (self.enableRolling)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
    }
    
    // 往下翻一张
    if (x >= 2 * _scrollView.frame.size.width)
    {
        _currentPage = [self getPageIndex:_currentPage+1];
        [self refreshScrollView];
    }

    if (x <= 0)
    {
        _currentPage = [self getPageIndex:_currentPage-1];
        [self refreshScrollView];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    _scrollView.contentOffset = CGPointMake(_scrollView.frame.size.width, 0);
    if (self.enableRolling)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
        [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.timeInterval inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    }
}


#pragma mark - Action
- (void)startRolling{
    if (self.imageArray.count == 0 || self.imageArray.count == 1){
        return;
    }
    
    [self stopRolling];
    
    self.enableRolling = YES;
    [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.timeInterval];
}

- (void)stopRolling{
    self.enableRolling = NO;
    //取消已加入的延迟线程
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
}

- (void)rollingScrollAction{
    // 滑动动画由我们自己完成
    [UIView animateWithDuration:0.25 animations:^{
        _scrollView.contentOffset = CGPointMake(1.99*_scrollView.frame.size.width, 0);
    } completion:^(BOOL finished) {
        if (finished)
        {
            _currentPage = [self getPageIndex:_currentPage+1];
            [self refreshScrollView];
            
            if (self.enableRolling)
            {
                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(rollingScrollAction) object:nil];
                [self performSelector:@selector(rollingScrollAction) withObject:nil afterDelay:self.timeInterval inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
            }
        }
    }];
}

- (void)handleTap:(UITapGestureRecognizer *)tap{
    if ([self.delegate respondsToSelector:@selector(infiniteScrollView:didSelectIndex:)]){
        [self.delegate infiniteScrollView:self didSelectIndex:_currentPage-1];
    }
}
@end