//
//  GMFacePlayer.m
//  GMAILab
//
//  Created by 卢悦明 on 2020/5/13.
//

#import "GMFacePlayer.h"

@interface GMFacePlayer (){
    NSTimer *_timer;
    BOOL _pauseByUser;
}
@end

@implementation GMFacePlayer
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_timer invalidate];
}

- (void)addProgressObserver {
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
                                            selector:@selector(timerFired)
                                            userInfo:nil
                                             repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    // 后台播放时视频会自动暂停，所以只管理timer就可以了。视频暂停时不需要暂停timer，因为currentTime不动，进度就不动
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(didBecomeActive)
                                                 name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(willResignActive)
                                                 name:UIApplicationWillResignActiveNotification
                                               object:nil];
}

- (void)willResignActive {
    // 重复pause可能存在问题，所以加判断
    if (self.isPlaying) {
        [self pause];
    }
}

- (void)didBecomeActive{
    // 拖动暂停 -> 后台 -> 前台，发现timer变成失效的了，所以加一段这个代码
    if (![_timer isValid]) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
                                                         selector:@selector(timerFired)
                                                         userInfo:nil
                                                          repeats:YES];
        
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    // 由用户暂停，然后后台 -> 前台，此时仍就维持暂停状态
    if (_pauseByUser) {
        return;
    }

    [self resume];
}

- (void)timerFired {
    [self updateTime];
    [self updateBeginTime];
    [self updateTotalTime];
    [self updateProgress];
}

- (void)updateTime {
    if (CMTIME_IS_INDEFINITE(self.totalDuration)) {
        return ;
    }

    self.current = CMTimeGetSeconds(self.currentTime);
    NSString *timeInfo = [NSString stringWithFormat:@"%@/%@",[self getMMSSFromSS:CMTimeGetSeconds(self.currentTime)],[self getMMSSFromSS:CMTimeGetSeconds(self.totalDuration)]];
    if ([self.progressDelegate respondsToSelector:@selector(updateTimeTitle:)]) {
        [self.progressDelegate updateTimeTitle:timeInfo];
    }
}

- (void)updateBeginTime {
    if (CMTIME_IS_INDEFINITE(self.totalDuration)) {
        return ;
    }

    self.current = CMTimeGetSeconds(self.currentTime);
    NSString *timeInfo = [NSString stringWithFormat:@"%@",[self getMMSSFromSS:CMTimeGetSeconds(self.currentTime)]];
    if ([self.progressDelegate respondsToSelector:@selector(updateBeginTimeTitle:)]) {
        [self.progressDelegate updateBeginTimeTitle:timeInfo];
    }
}

- (void)updateTotalTime {
    if (CMTIME_IS_INDEFINITE(self.totalDuration)) {
        return ;
    }

    self.current = CMTimeGetSeconds(self.currentTime);
    NSString *timeInfo = [NSString stringWithFormat:@"%@",[self getMMSSFromSS:CMTimeGetSeconds(self.totalDuration)]];
    if ([self.progressDelegate respondsToSelector:@selector(updateTotalTimeTitle:)]) {
        [self.progressDelegate updateTotalTimeTitle:timeInfo];
    }
}

- (void)updateProgress {
    if (CMTIME_IS_INDEFINITE(self.totalDuration)) {
        return ;
    }

    CGFloat progress = CMTimeGetSeconds(self.currentTime)/CMTimeGetSeconds(self.totalDuration);
    if (fabs(progress - 1) < 0.01 || CMTimeGetSeconds(self.currentTime) > CMTimeGetSeconds(self.totalDuration)) {
        [self pauseTimer];
        progress = 1;
    }
    if ([self.progressDelegate respondsToSelector:@selector(updateProgress:)]) {
        [self.progressDelegate updateProgress:progress];
    }
}

-(NSString *)getMMSSFromSS:(float)totalTime {
    NSInteger seconds = totalTime;
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02d", (int)(seconds/3600)];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02d",(int)((seconds%3600)/60)];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02d",(int)(seconds%60)];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@", str_hour, str_minute, str_second];
    return format_time;
}

- (void)seekToProgress:(CGFloat)value {
    long long time = ceil(CMTimeGetSeconds(self.totalDuration) * value);
    [self seekTo:CMTimeMake(time, 1)];
    [self updateTime];
}

- (void)stop{
    [super stop];
    [_timer invalidate];
}

- (void)resume {
    [super resume];
    _pauseByUser = NO;
}

- (void)pauseTimer{
    [_timer invalidate];
    _timer = nil;
}

- (void)resumeTimer{
    [_timer invalidate];
    _timer = nil;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self
                                            selector:@selector(timerFired)
                                            userInfo:nil
                                             repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)pausePlayer {
    _pauseByUser = YES;
    [self pause];
}
@end

