//
//  RCTVideoToolbar.m
//  RCTOMPlayer
//
//  Created by lcg on 2017/7/14.
//  Copyright © 2017年 Anren. All rights reserved.
//

#import "RCTVideoToolbar.h"
#import "JX_GCDTimerManager.h"

#import "RCTToolbarSlider.h"

#define SLIDER_TIMER @"om_video_slider"
#import <UIKit/UIKit.h>
@interface LPBgFrameButton : UIButton
@end

@implementation LPBgFrameButton
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event{
    CGRect bounds = self.bounds;
    //若原热区小于44x44，则放大热区，否则保持原大小不变
    CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
    CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(bounds, point);
}
@end

@interface RCTVideoToolbar()

@property (nonatomic, weak) UIButton *btnPlayPause;
@property (nonatomic, weak) UIButton *btnPlayRate;
@property (nonatomic, weak) UILabel *lblCurrentTime;
@property (nonatomic, weak) UISlider *sliderProgress;
//@property (nonatomic, weak) UILabel *lblTotalTime;
@property (nonatomic, weak) UIButton *btnFullscreen;
@property (nonatomic, assign) BOOL dragging;

@end

@implementation RCTVideoToolbar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initControlls];
        [self initConstraints];
    }
    return self;
}

- (void) initControlls
{
    UIButton *btnPlayPause = [[LPBgFrameButton alloc] init];
    [btnPlayPause setBackgroundImage:[UIImage imageNamed:@"ic_play.png"] forState:UIControlStateNormal];
    [btnPlayPause addTarget:self action:@selector(playPauseTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *btnPlayRate = [[LPBgFrameButton alloc] init];
    btnPlayRate.tag = 123;
    [btnPlayRate setTitle:@"倍速" forState:UIControlStateNormal];
    [btnPlayRate setTitleColor:[UIColor redColor] forState:UIControlStateFocused | UIControlStateSelected | UIControlStateHighlighted];
    btnPlayRate.titleLabel.font = [UIFont systemFontOfSize: 15];
    [btnPlayRate addTarget:self action:@selector(rateTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    btnPlayRate.hidden = YES;
    
    UIButton *btnFullscreen = [[LPBgFrameButton alloc] init];
    [btnFullscreen setBackgroundImage:[UIImage imageNamed:@"enlarge_fullscreen.png"] forState:UIControlStateNormal];
    [btnFullscreen addTarget:self action:@selector(fullscreenTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *lblCurrentTime = [[UILabel alloc] init];
    [lblCurrentTime setTextColor:[UIColor whiteColor]];
    [lblCurrentTime setFont:[UIFont systemFontOfSize:11.0f]];
    [lblCurrentTime setText:@"--:--/--:--"];
    
    //    UILabel *lblTotalTime = [[UILabel alloc] init];
    //    [lblTotalTime setTextColor:[UIColor whiteColor]];
    //    [lblTotalTime setFont:[UIFont systemFontOfSize:11.0f]];
    //    [lblTotalTime setText:@"--:--"];
    
    UIImage *thumb = [UIImage imageNamed:@"ic_circles.png"];
    RCTToolbarSlider *sliderProgress = [[RCTToolbarSlider alloc] init];
    
    //    sliderProgress.backgroundColor = [UIColor greenColor];
    [sliderProgress setMinimumTrackImage:[UIImage imageNamed:@"progress_green_mid.png"] forState:UIControlStateNormal];
    [sliderProgress setMaximumTrackImage:[UIImage imageNamed:@"progress_gray_mid.png"] forState:UIControlStateNormal];
    sliderProgress.minimumValueImage = [UIImage imageNamed:@"progress_green_left.png"];
    sliderProgress.maximumValueImage = [UIImage imageNamed:@"progress_gray_right.png"];
    sliderProgress.continuous = NO;
    [sliderProgress setMinimumValue:0];
    [sliderProgress setMaximumValue:0];
    [sliderProgress setValue:0 animated:NO];
    [sliderProgress setThumbImage:thumb forState:UIControlStateNormal];
    [sliderProgress addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    [sliderProgress addTarget:self action:@selector(sliderTouchUp:) forControlEvents:UIControlEventTouchUpInside];
    [sliderProgress addTarget:self action:@selector(sliderTouchUp:) forControlEvents:UIControlEventTouchUpOutside];
    [sliderProgress addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    btnPlayPause.translatesAutoresizingMaskIntoConstraints = NO;
    btnPlayRate.translatesAutoresizingMaskIntoConstraints = NO;
    btnFullscreen.translatesAutoresizingMaskIntoConstraints = NO;
    lblCurrentTime.translatesAutoresizingMaskIntoConstraints = NO;
    //    lblTotalTime.translatesAutoresizingMaskIntoConstraints = NO;
    sliderProgress.translatesAutoresizingMaskIntoConstraints = NO;

    
    [self addSubview:btnPlayPause];
    [self addSubview:btnPlayRate];
    [self addSubview:lblCurrentTime];
    [self addSubview:sliderProgress];
    //    [self addSubview:lblTotalTime];
    [self addSubview:btnFullscreen];
    
    self.btnPlayPause = btnPlayPause;
    self.btnPlayRate = btnPlayRate;
    self.btnFullscreen = btnFullscreen;
    self.lblCurrentTime = lblCurrentTime;
    //    self.lblTotalTime = lblTotalTime;
    self.sliderProgress = sliderProgress;
}

- (void)setPlayPauseConstraints
{
    NSLayoutConstraint *marginLeft = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self
                                                                  attribute:NSLayoutAttributeLeft
                                                                 multiplier:1
                                                                   constant:20];
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1
                                                              constant:25];
    
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeNotAnAttribute
                                                             multiplier:1
                                                               constant:25];
    
    [self addConstraints:[NSArray arrayWithObjects:marginLeft,hCenter,width,height, nil]];
}

- (void)setCurrentTimeConstraints
{
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.lblCurrentTime
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeLeft
                                                                  multiplier:1
                                                                    constant:-16];
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.lblCurrentTime
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    [self addConstraints:[NSArray arrayWithObjects:marginRight, hCenter, nil]];
}

- (void)setSliderProgressConstraints
{
    NSLayoutConstraint *marginLeft = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.btnPlayPause
                                                                  attribute:NSLayoutAttributeRight
                                                                 multiplier:1
                                                                   constant:20];
    
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeLeft
                                                                  multiplier:1
                                                                    constant:-93];
    
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    [self addConstraints:[NSArray arrayWithObjects:marginLeft, marginRight, hCenter, nil]];
}

- (void)setFullscreenConstraints
{
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self
                                                                   attribute:NSLayoutAttributeRight
                                                                  multiplier:1
                                                                    constant:-15];
    
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1
                                                              constant:18];
    
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeNotAnAttribute
                                                             multiplier:1
                                                               constant:18];
    
    [self addConstraints:[NSArray arrayWithObjects:marginRight, hCenter, width, height, nil]];
}

-(void) initConstraints {
    [self setPlayPauseConstraints];
    [self setFullscreenConstraints];
    [self setCurrentTimeConstraints];
    [self setSliderProgressConstraints];
}

- (void)setFullConstraints
{
    [self setPlayPauseFullConstraints];
    [self setPlayRateFullConstraints];
    [self setFullscreenFullConstraints];
    [self setCurrentTimeFullConstraints];
    [self setSliderProgressFullConstraints];
}

- (void)setPlayPauseFullConstraints
{
    NSLayoutConstraint *marginLeft = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self
                                                                  attribute:NSLayoutAttributeLeft
                                                                 multiplier:1
                                                                   constant:20];
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1
                                                              constant:25];
    
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.btnPlayPause
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeNotAnAttribute
                                                             multiplier:1
                                                               constant:25];
    
    [self addConstraints:[NSArray arrayWithObjects:marginLeft,hCenter,width,height, nil]];
}

- (void)setCurrentTimeFullConstraints
{
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.lblCurrentTime
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self.btnPlayRate
                                                                   attribute:NSLayoutAttributeLeft
                                                                  multiplier:1
                                                                    constant:-10];
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.lblCurrentTime
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    [self addConstraints:[NSArray arrayWithObjects:marginRight, hCenter, nil]];
}

- (void)setPlayRateFullConstraints
{
    NSLayoutConstraint *marginLeft = [NSLayoutConstraint constraintWithItem:self.btnPlayRate
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.lblCurrentTime
                                                                  attribute:NSLayoutAttributeRight
                                                                 multiplier:1
                                                                   constant:-10];
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.btnPlayRate
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeLeft
                                                                  multiplier:1
                                                                    constant:-15];
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.btnPlayRate
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    [self addConstraints:[NSArray arrayWithObjects:marginLeft, marginRight, hCenter, nil]];
}

- (void)setSliderProgressFullConstraints
{
    NSLayoutConstraint *marginLeft = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                                  attribute:NSLayoutAttributeLeft
                                                                  relatedBy:NSLayoutRelationEqual
                                                                     toItem:self.btnPlayPause
                                                                  attribute:NSLayoutAttributeRight
                                                                 multiplier:1
                                                                   constant:20];
    
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeLeft
                                                                  multiplier:1
                                                                    constant:-133];
    
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.sliderProgress
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    [self addConstraints:[NSArray arrayWithObjects:marginLeft, marginRight, hCenter, nil]];
}

- (void)setFullscreenFullConstraints
{
    NSLayoutConstraint *marginRight = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                                   attribute:NSLayoutAttributeRight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:self
                                                                   attribute:NSLayoutAttributeRight
                                                                  multiplier:1
                                                                    constant:-20];
    
    NSLayoutConstraint *hCenter = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                               attribute:NSLayoutAttributeCenterY
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self
                                                               attribute:NSLayoutAttributeCenterY
                                                              multiplier:1
                                                                constant:0];
    
    NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                             attribute:NSLayoutAttributeWidth
                                                             relatedBy:NSLayoutRelationEqual
                                                                toItem:nil
                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                            multiplier:1
                                                              constant:18];
    
    NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:self.btnFullscreen
                                                              attribute:NSLayoutAttributeHeight
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:nil
                                                              attribute:NSLayoutAttributeNotAnAttribute
                                                             multiplier:1
                                                               constant:18];
    
    [self addConstraints:[NSArray arrayWithObjects:marginRight, hCenter, width, height, nil]];
}

- (void)sliderTouchDown:(id)sender
{
    self.dragging = YES;
}

- (void)sliderTouchUp:(id)sender
{
    NSLog(@"*********sliderTouchUp************");
    
    [[JX_GCDTimerManager sharedInstance] scheduledDispatchTimerWithName:SLIDER_TIMER
                                                           timeInterval:0.3
                                                                  queue:nil
                                                                repeats:NO
                                                           actionOption:AbandonPreviousAction
                                                                 action:^{
                                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                                         self.dragging = NO;
                                                                     });
                                                                 }];
}

- (void)sliderValueChanged:(id)sender
{
    NSLog(@"*********sliderValueChanged************");
    if (self.delegate && [self.delegate respondsToSelector:@selector(seekTo:)])
    {
        [self.delegate seekTo:self.sliderProgress.value];
    }
}

- (void)playPauseTouchUp:(id)sender
{
    if (self.delegate)
    {
        if (self.paused && [self.delegate respondsToSelector:@selector(play)])
        {
            [self.delegate play];
        }
        else if (!self.paused && [self.delegate respondsToSelector:@selector(pause)])
        {
            [self.delegate pause];
        }
    }
}

- (void)rateTouchUp:(id)sender
{
    [self.delegate rated: YES];
}


- (void)fullscreenTouchUp:(id)sender
{
    if (self.delegate)
    {
        if (self.fullscreen && [self.delegate respondsToSelector:@selector(shrink)])
        {
            self.btnPlayRate.hidden = NO;
            [self.delegate shrink];
        }
        else if (!self.fullscreen && [self.delegate respondsToSelector:@selector(expand)])
        {
            self.btnPlayRate.hidden = NO;
            [self.delegate expand];
        }
    }
}

- (void)setCurrentTime:(float)currentTime
{
    _currentTime = currentTime;
    
    [self.lblCurrentTime setText:[NSString stringWithFormat:@"%@/%@", [self formatTime:currentTime], [self formatTime: self.totalTime]]];
    
    if (!self.dragging)
    {
        [self.sliderProgress setValue:currentTime];
    }
}

- (void)setTotalTime:(float)totalTime
{
    _totalTime = totalTime;
    
    [self.lblCurrentTime setText:[NSString stringWithFormat:@"%@/%@", [self formatTime:self.currentTime], [self formatTime: totalTime]]];
    [self.sliderProgress setMaximumValue:totalTime];
}

- (void)setPaused:(BOOL)paused
{
    _paused = paused;
    
    if (paused)
    {
        [self.btnPlayPause setBackgroundImage:[UIImage imageNamed:@"ic_play.png"] forState:UIControlStateNormal];
    }
    else
    {
        [self.btnPlayPause setBackgroundImage:[UIImage imageNamed:@"ic_pause.png"] forState:UIControlStateNormal];
    }
}

- (void)setFullscreen:(BOOL)fullscreen
{
    _fullscreen = fullscreen;
    if (fullscreen)
    {
        [self removeConstraints: [self constraints]];
        self.btnPlayRate.hidden = NO;
        [self setFullConstraints];
        [self.btnFullscreen setBackgroundImage:[UIImage imageNamed:@"shrink_fullscreen@2x.png"] forState:UIControlStateNormal];
    }
    else
    {
        [self removeConstraints: [self constraints]];
        self.btnPlayRate.hidden = YES;
        [self initConstraints];
        [self.btnFullscreen setBackgroundImage:[UIImage imageNamed:@"enlarge_fullscreen.png"] forState:UIControlStateNormal];
    }
}

- (NSString*)formatTime:(int)time
{
    int totalSec = time;
    
    int sec = totalSec % 60;
    int min = totalSec / 60;
    
    NSString *formatTime = [NSString stringWithFormat:@"%02d:%02d",min,sec];
    
    return formatTime;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
}

@end
