//
//  PlayerView.m
//  VclustersGemini
//
//  Created by APPLE on 2019/6/13.
//  Copyright © 2019 APPLE. All rights reserved.
//

#import "PlayerView.h"
#import "UIView+View.h"


@interface PlayerView ()
<UIGestureRecognizerDelegate,
ShowImageViewDelegate>{
    EAGLContext *eagContext;
    CIContext *ciContext;
    CIFilter *filter;
    
    //触控指令视图,用于计算触控位置坐标
    ShowImageView *touchCommondView;
    
    UIView *bottomContrView;
    
    UIButton *mueBtn;
    UIButton *homeBtn;
    UIButton *backBtn;
    
    UIButton *showHomeBtn;
    
    NSTimer *hideBottomTimer;
}

@end


@implementation PlayerView
@synthesize showImageView;
@synthesize glkshowImageView;
@synthesize controlBtn;
@synthesize delegate;
@synthesize isLan;

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    
    if (self){
        [self setBackgroundColor:[UIColor blackColor]];
        [self initOpenGL];
        
        [self drawView:frame];
    }
    
    return self;
}

- (void)initOpenGL{
    eagContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    ciContext = [CIContext contextWithEAGLContext:eagContext
                                          options:@{kCIContextWorkingColorSpace:[NSNull null]}];
    
    filter = [CIFilter filterWithName:@"CISepiaTone"];
}

- (void)glkShowImage:(CIImage *)ciImage{
    [filter setValue:ciImage forKey:kCIInputImageKey];
    [filter setValue:@(0)    forKey:kCIInputIntensityKey];
    
    //开始渲染
    [ciContext drawImage:[filter valueForKey:kCIOutputImageKey]
                  inRect:CGRectMake(0, 0, glkshowImageView.drawableWidth, glkshowImageView.drawableHeight)
                fromRect:[ciImage extent]];
    
    [self->glkshowImageView display];
}

- (void)showIMage
{
    ;
}


- (void)drawView:(CGRect)frame{
    self.frame = frame;
    
    touchCommondView = [[ShowImageView alloc] init];
    [touchCommondView setBackgroundColor:  [UIColor clearColor]];
    [touchCommondView setUserInteractionEnabled:YES];
    touchCommondView.multipleTouchEnabled = YES;
    touchCommondView.delegate = self;
    [self addSubview:touchCommondView];

    [touchCommondView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0.f);
        make.height.mas_equalTo(frame.size.height);
        make.right.mas_equalTo(0.f);
        make.top.mas_equalTo(0.f);
    }];
    
    //此方案弃用
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapBeganFun)];
//    [touchCommondView addGestureRecognizer:tap];
    
    /*播放视图*/
    showImageView = [[ShowImageView alloc] init];
    [showImageView setBackgroundColor:  [UIColor blackColor]];
    [showImageView setUserInteractionEnabled:NO];
    
    [showImageView setBackgroundColor:[UIColor blackColor]];
    glkshowImageView = [[GLKView alloc] initWithFrame:self.frame context:eagContext];
    [glkshowImageView setBackgroundColor:[UIColor blackColor]];
    [glkshowImageView bindDrawable];
    [glkshowImageView setUserInteractionEnabled:NO];
    
    [touchCommondView addSubview:showImageView];

    [showImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
        make.bottom.mas_equalTo(0.f);
        make.top.mas_equalTo(0.f);
    }];
    
    
    [touchCommondView addSubview:glkshowImageView];
    [glkshowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
        make.bottom.mas_equalTo(0.f);
        make.top.mas_equalTo(0.f);
    }];

    /*控制按钮*/
    UIImage  *driftBtnImage = [UIImage imageNamed:@"you_icon"];
    controlBtn = [[UIButton alloc] init];
    [controlBtn setBackgroundColor:[UIColor clearColor]];
    [controlBtn addTarget:self
                     action:@selector(controlBtnPressed:)
           forControlEvents:(UIControlEventTouchUpInside)];
    
    UIPanGestureRecognizer *gester = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureCallback:)];
    [controlBtn addGestureRecognizer:gester];
    gester.delegate = self;
    gester = nil;
    
    //[controlBtn setImage:driftBtnImage forState:(UIControlStateNormal)];
    [controlBtn setBackgroundImage:driftBtnImage forState:(UIControlStateNormal)];
    [controlBtn addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(controlBtnLongPress:)]];
    
    /*下方控制器*/
    bottomContrView = [[UIView alloc] initWithFrame:CGRectMake(0, frame.size.height - 47.f, frame.size.width, 47.f)];
    [bottomContrView setBackgroundColor:[UIColor blackColor]];
    [self addSubview:bottomContrView];
    [bottomContrView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(47.f);
        make.left.mas_equalTo(0.f);
        make.bottom.mas_equalTo(0.f);
    }];
    [bottomContrView setHidden:YES];
    
    [self initAddSubViewForBottomContrView];
    
    [self setPoMas_makeWithImageRate:frame.size.width/frame.size.height isOpenVirtual:NO isUsageMode:NO];
    
    
}

- (void)initAddSubViewForBottomContrView{
    /*第一个app菜单*/
    UIImage  *mueBtnImage = [UIImage imageNamed:@"houtai_icon"];
    mueBtn = [[UIButton alloc] init];
    [mueBtn setBackgroundColor:[UIColor clearColor]];
    [mueBtn addTarget:self
               action:@selector(mueBtnPressed:)
     forControlEvents:(UIControlEventTouchUpInside)];
    [mueBtn setImage:mueBtnImage forState:(UIControlStateNormal)];
    [mueBtn setImageEdgeInsets:(UIEdgeInsetsMake(6.f, 6.f, 6.f, 6.f))];
    [bottomContrView addSubview:mueBtn];
    
    /*第二个home键*/
    UIImage  *homeBtnImage = [UIImage imageNamed:@"home_icon"];
    homeBtn = [[UIButton alloc] init];
    [homeBtn setBackgroundColor:[UIColor clearColor]];
    [homeBtn addTarget:self
                action:@selector(homeBtnPressed:)
      forControlEvents:(UIControlEventTouchUpInside)];
    [homeBtn setImage:homeBtnImage forState:(UIControlStateNormal)];
    [homeBtn setImageEdgeInsets:(UIEdgeInsetsMake(6.f, 6.f, 6.f, 6.f))];
    [bottomContrView addSubview:homeBtn];
    
    /*第三个返回键*/
    UIImage  *backBtnImage = [UIImage imageNamed:@"fanhui_you_icon"];
    backBtn = [[UIButton alloc] init];
    [backBtn setBackgroundColor:[UIColor clearColor]];
    [backBtn addTarget:self
                action:@selector(backBtnPressed:)
      forControlEvents:(UIControlEventTouchUpInside)];
    [backBtn setImage:backBtnImage forState:(UIControlStateNormal)];
    [backBtn setImageEdgeInsets:(UIEdgeInsetsMake(6.f, 6.f, 6.f, 6.f))];
    [bottomContrView addSubview:backBtn];
    //测试说图片方向反了
    backBtn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    
    /*第四个隐藏显示键*/
    UIImage  *showBtnImage = [UIImage imageNamed:@"showOrhide_home_icon"];
    showHomeBtn = [[UIButton alloc] init];
    [showHomeBtn setBackgroundColor:[UIColor clearColor]];
    [showHomeBtn addTarget:self action:@selector(showOrHideHomeButtomFun:) forControlEvents:(UIControlEventTouchUpInside)];
    [showHomeBtn setImage:showBtnImage forState:(UIControlStateNormal)];
    [showHomeBtn setImageEdgeInsets:(UIEdgeInsetsMake(6.f, 6.f, 6.f, 6.f))];
    [bottomContrView addSubview:showHomeBtn];
}

- (void)mueBtnPressed:(id)sender{
    if ([delegate respondsToSelector:@selector(mueBtnBePressed:)]) {
        [delegate mueBtnBePressed:sender];
    }
}


- (void)homeBtnPressed:(id)sender{
    if ([delegate respondsToSelector:@selector(homeBtnBePressed:)]) {
        [delegate homeBtnBePressed:sender];
    }
}

- (void)backBtnPressed:(id)sender{
    if ([delegate respondsToSelector:@selector(backBtnBePressed:)]) {
        [delegate backBtnBePressed:sender];
    }
}

- (void)showOrHideHomeButtomFun:(UIButton*)but{
    but.selected = !but.selected;
    
    if(but.selected){
        but.imageView.transform = CGAffineTransformMakeRotation(M_PI);
    }
    else{
        but.imageView.transform = CGAffineTransformMakeRotation(0);
    }
    
    [self setShowOrHideBottomButtonsFunBy:but.selected];
}

- (void)initPoMas_makeWithImageRate:(BOOL)isOpenVirtual isUsageMode:(BOOL)isUsageMode{
    [self setPoMas_makeWithImageRate:self.frame.size.width/self.frame.size.height isOpenVirtual:isOpenVirtual isUsageMode:isUsageMode];
}

- (void)setPoMas_makeWithImageRate:(CGFloat)w_h_rate isOpenVirtual:(BOOL)isOpenVirtual isUsageMode:(BOOL)isUsageMode{
    /*播放视图*/
//    touchCommondView.isLan = NO;
    [showImageView setBackgroundColor:[UIColor blackColor]];
    [touchCommondView mas_remakeConstraints:^(MASConstraintMaker *make) {
        CGFloat scr_W = SCREEN_W;
        CGFloat scr_H = SCREEN_H;
        if (SCREEN_W > SCREEN_H){
            scr_W = SCREEN_H;
            scr_H = SCREEN_W;
        }
        if ((scr_H - scr_W/w_h_rate - 40.f)/2.f < 0){
            make.height.mas_equalTo(scr_H - 40.f);
            make.width.mas_equalTo((scr_H - 40.f)*w_h_rate);
            make.centerX.equalTo(self.mas_centerX);
            make.top.mas_equalTo(0);
        }
        else{
            make.left.mas_equalTo(0.f);
            make.height.mas_equalTo(scr_W/w_h_rate);
            make.right.mas_equalTo(0.f);
            make.top.mas_equalTo((scr_H - scr_W/w_h_rate - 40.f)/2.f);
        }
    }];
    
    [showImageView    setTransform:CGAffineTransformMakeRotation(0)];
    [glkshowImageView setTransform:CGAffineTransformMakeRotation(0)];
    
    [showImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(touchCommondView.mas_left);
        make.right.equalTo(touchCommondView.mas_right);
        make.top.equalTo(touchCommondView.mas_top);
        make.bottom.equalTo(touchCommondView.mas_bottom);
    }];
    [self.glkshowImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(touchCommondView.mas_left);
        make.right.equalTo(touchCommondView.mas_right);
        make.top.equalTo(touchCommondView.mas_top);
        make.bottom.equalTo(touchCommondView.mas_bottom);
    }];
    
    [bottomContrView setHidden:NO];
    [bottomContrView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(40.f);
        make.right.equalTo(touchCommondView.mas_right);
        make.top.equalTo(touchCommondView.mas_bottom);
        make.left.equalTo(touchCommondView.mas_left);
    }];

    [mueBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(80.f);
        make.width.and.height.mas_equalTo(40.f);
        make.top.mas_equalTo(0);
    }];

    [homeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomContrView.mas_centerX);
        make.width.and.height.mas_equalTo(40.f);
        make.top.mas_equalTo(0);
    }];

    UIImage  *backBtnImage = [UIImage imageNamed:@"fanhui_you_icon"];
//        UIImage  *backBtnImage = [UIImage imageNamed:@"fanhui_icon"];
    [backBtn setImage:backBtnImage forState:(UIControlStateNormal)];
    [backBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-80.f);
        make.width.and.height.mas_equalTo(40.f);
        make.top.mas_equalTo(0);
    }];
    
    [showHomeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-20.f);
        make.width.and.height.mas_equalTo(40.f);
        make.top.mas_equalTo(0);
    }];
}

/**
 * @brief 设置横屏模式UI布局
 *
 * @param  w_h_rate 宽高比
 *
 * @param isOpenVirtual 是否有打开底部虚拟按键
 *
 * @param isUsageMode 是否为专业模式
 *
 */
- (void)setLanMas_makeWithImageRate:(CGFloat)w_h_rate isOpenVirtual:(BOOL)isOpenVirtual isUsageMode:(BOOL)isUsageMode{
    /*需要考虑专业模式*/

    /*暂时只考虑非专业模式无虚拟键布局*/
    CGFloat h_forPhoneTop = 0;
    if (IPHONE_X){
        h_forPhoneTop = 44.f;
    }
    CGFloat des_W = SCREEN_W<SCREEN_H?SCREEN_W:SCREEN_H;/*实际较小的数字*/
    CGFloat des_H = (SCREEN_W>SCREEN_H?SCREEN_W:SCREEN_H) - h_forPhoneTop;/*实际较大的数字*/
//    touchCommondView.isLan = YES;
    [touchCommondView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0.f);
        make.width.mas_equalTo(des_W*w_h_rate);
        make.left.mas_equalTo(h_forPhoneTop + (des_H - des_W*w_h_rate)/2.f);
        make.top.mas_equalTo(0);
    }];
    
    CGFloat des_H1 = des_W*w_h_rate;/*实际较大的数字*/
    CGFloat des_W1 = des_W;/*实际较小的数字*/
    if (isUsageMode){
        des_W1 = des_W-44.f;
        des_H1 = (des_W-44.f)*w_h_rate;
    }
    [showImageView    setTransform:CGAffineTransformMakeRotation(-M_PI/2)];
    [glkshowImageView setTransform:CGAffineTransformMakeRotation(-M_PI/2)];
    
    [showImageView setBackgroundColor:[UIColor blackColor]];
    [showImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(des_H1);
        make.width.mas_equalTo((des_W1));
        make.left.mas_equalTo((des_H1 - des_W1)/2.f);
        make.top.mas_equalTo((des_W1 - des_H1)/2.f);
    }];

    [self.glkshowImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        /*动态处理宽高*/
        make.height.mas_equalTo(des_H1);
        make.width.mas_equalTo((des_W1));
        make.left.mas_equalTo((des_H1 - des_W1)/2.f);
        make.top.mas_equalTo((des_W1 - des_H1)/2.f);
    }];
}


- (void)controlBtnPressed:(id)sender{
    if ([delegate respondsToSelector:@selector(useInfoBtnBePressed:)]) {
        [delegate useInfoBtnBePressed:sender];
    }
}


static int sendCount = 0;
#pragma -mark showImageViewDelegate
- (void)showImageViewtouchesBeganCommondStr:(NSString *)commondStr{
    if ([delegate respondsToSelector:@selector(playerShowImageViewtouchesStr:)]){
        sendCount = 1;
        [delegate playerShowImageViewtouchesStr:commondStr];
        HLog(@"\n-----showImageViewtouchesBeganCommondStr-----");
    }
}

- (void)showImageViewtouchesEndedCommondStr:(NSString *)commondStr{
    if ([delegate respondsToSelector:@selector(playerShowImageViewtouchesStr:)]){
        HLog(@"\n-----showImageViewtouchesEndedCommondStr-----");
        sendCount = 0;
        [delegate playerShowImageViewtouchesStr:commondStr];
    }
}

- (void)showImageViewtouchesMovedCommondStr:(NSString *)commondStr{
    if ([delegate respondsToSelector:@selector(playerShowImageViewtouchesStr:)]){
        HLog(@"\n-----showImageViewtouchesMovedCommondStr-----");
        if (sendCount%2 == 0){
            [delegate playerShowImageViewtouchesStr:commondStr];
        }
        
        sendCount++;
    }
}

- (void)showImageViewtouchesCancelledCommondStr:(NSString *)commondStr{
    if ([delegate respondsToSelector:@selector(playerShowImageViewtouchesStr:)]){
        HLog(@"\n-----showImageViewtouchesCancelledCommondStr-----");
        sendCount = 0;
        [delegate playerShowImageViewtouchesStr:commondStr];
    }
}

- (void)controlBtnLongPress:(UILongPressGestureRecognizer *)longPressGesture {
    
    switch (longPressGesture.state) {
        case UIGestureRecognizerStateBegan:{
//            HLog(@"云手机推流界面 控制按钮长按手势开始");
            [[NSNotificationCenter defaultCenter] postNotificationName:PlayerViewControlBtnTouchBeganNotification object:nil userInfo:nil];
            
            break;
        case UIGestureRecognizerStateEnded:{
//            HLog(@"云手机推流界面 控制按钮长按手势结束");
            [[NSNotificationCenter defaultCenter] postNotificationName:PlayerViewControlBtnTouchEndNotification object:nil userInfo:nil];
            break;
            }
        default:
            break;
        }
    }
}

static CGRect startFrame;
- (void)panGestureCallback:(UIPanGestureRecognizer *)panGesture{
    self.controlBtn.alpha = 1;
    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:{
            startFrame = controlBtn.frame;
            
//            HLog(@"云手机推流界面 控制按钮拖动手势开始");
            [[NSNotificationCenter defaultCenter] postNotificationName:PlayerViewControlBtnTouchBeganNotification object:nil userInfo:nil];
            
            break;
        }
        case UIGestureRecognizerStateChanged:{
            CGPoint translatedPoint = [panGesture translationInView:self];/*KXLY*/
            CGRect frame = controlBtn.frame;
            frame.origin.x = translatedPoint.x + startFrame.origin.x;
            frame.origin.y = translatedPoint.y + startFrame.origin.y;
            controlBtn.frame = frame;
            
//            HLog(@"\n--(%f,%f)--controlBtn.frame--X-%f",translatedPoint.x,translatedPoint.x,controlBtn.frame.origin.x);
            
            break;
        }
        case UIGestureRecognizerStateEnded:
//                HLog(@"云手机推流界面 控制按钮拖动手势结束");
            [[NSNotificationCenter defaultCenter] postNotificationName:PlayerViewControlBtnTouchEndNotification object:nil userInfo:nil];
            /*防止控制器移出屏幕*/
            CGRect frame = controlBtn.frame;
            if (frame.origin.x < 10.f/2.f){
                frame.origin.x = 10.f/2.f;
            }
            if (frame.origin.y < 10.f/2.f + H_STATE_BAR){
                frame.origin.y = 10.f/2.f + H_STATE_BAR;
            }
            if (frame.size.width + frame.origin.x + 10.f/2.f > self.width){
                frame.origin.x = self.width - 10.f/2.f - frame.size.width;
            }
            if (frame.size.height + frame.origin.y + 10.f/2.f > self.height){
                frame.origin.y = self.height - 10.f/2.f - frame.size.height;
            }
            
            controlBtn.frame = frame;
            break;
        case UIGestureRecognizerStateCancelled: {
            /*防止控制器移出屏幕*/
            CGRect frame = controlBtn.frame;
            if (frame.origin.x < 10.f/2.f){
                frame.origin.x = 10.f/2.f;
            }
            if (frame.origin.y < 10.f/2.f + H_STATE_BAR){
                frame.origin.y = 10.f/2.f + H_STATE_BAR;
            }
            if (frame.size.width + frame.origin.x + 10.f/2.f > self.width){
                frame.origin.x = self.width - 10.f/2.f - frame.size.width;
            }
            if (frame.size.height + frame.origin.y + 10.f/2.f > self.height){
                frame.origin.y = self.height - 10.f/2.f - frame.size.height;
            }
            
            controlBtn.frame = frame;
                        
            break;
        }
        default:
            break;
    }
}

- (void)setIsLan:(BOOL)isLan{
    self->isLan = isLan;
    
    /*设置视图方向*/
    showImageView.isLan = isLan;
    touchCommondView.isLan = isLan;
    
    //[self setShowOrHideBottomButtonsFunBy:isLan];
}

- (void)setShowOrHideBottomButtonsFunBy:(BOOL)isHide
{
    mainBlock(^{
        self->mueBtn.hidden = isHide;
        self->homeBtn.hidden = isHide;
        self->backBtn.hidden = isHide;
    });
}

#pragma mark 点击屏幕出来
- (void)didTapBeganFun
{
    if(!isLan){
        return;
    }
    
//    if(![commondStr containsString:@"\"count\":1"]){
//        return;
//    }
    
    if(mueBtn.hidden){
        [self setShowOrHideBottomButtonsFunBy:NO];
        
        [hideBottomTimer invalidate];
        hideBottomTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerToHideBottomButtonFun) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:hideBottomTimer forMode:NSRunLoopCommonModes];
    }
    else{
        [self setShowOrHideBottomButtonsFunBy:YES];
        [hideBottomTimer invalidate];
    }
}

- (void)timerToHideBottomButtonFun
{
    [hideBottomTimer invalidate];
    
    if(!isLan){
        return;
    }
    [self setShowOrHideBottomButtonsFunBy:YES];
}
@end
