//
//  BJPViewController.m
//  BJPlaybackUI
//
//  Created by oushizishu on 08/22/2017.
//  Copyright (c) 2017 oushizishu. All rights reserved.
//

#import <BJPlaybackUI/BJPlaybackUI.h>
#import <BJVideoPlayerUI/BJVideoPlayerUI.h>

#import "BJPViewController.h"
#import "PUPlayOptionsManager.h"

@interface BJPViewController ()<UIActionSheetDelegate, UIAlertViewDelegate>

@property (nonatomic) UITextField *classIDTextField, *tokenTextField, *sessionIDTextField,
                                  *userInfoTextField, *userNumaberTextField, *clipedVersionTextField;
@property (strong, nonatomic) UITextField *videoUrlTextField;
@property (nonatomic) UIScrollView *scrollView;
@property (nonatomic, readwrite) UIView *contentView;

@end

@implementation BJPViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
#if (__IPHONE_OS_VERSION_MAX_ALLOWED >= 130000) // __IPHONE_13_0
    if (@available(iOS 13.0, *)) {
        self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
#endif
    [self setupViews];
    
//    self.classIDTextField.text = @"";
//    self.sessionIDTextField.text = @"";
//    self.tokenTextField.text = @"";
//    self.videoUrlTextField.text = @"";
    
}

- (void)setupViews {
    [self setupScrollView];
    [self setupClassIDTextField];
    [self setupSessionIDTextField];
    [self setuptokenTextField];
    [self setupUserInfoTextField];
    [self setupUserNumberTextField];
    [self setupClipedVersionTextField];
    [self setupVideoUrlTextField];
    [self setupButton];
}

- (void)setupScrollView {
    self.contentView = [UIView new];
    self.scrollView = [UIScrollView new];
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, self.view.frame.size.height+50);
    
    [self.scrollView addSubview:self.contentView];
    [self.view addSubview:self.scrollView];
    
    [self.contentView bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.width.equalTo(self.view);
        make.height.equalTo(self.view).multipliedBy(1.3);
        make.top.left.equalTo(self.scrollView);
    }];
    [self.scrollView bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)setupClassIDTextField {
    NSString *classID = @"18121856439323";
    self.classIDTextField = [self textFieldwithContent:classID leftLabelText:@"教室id: "];
    [self.contentView addSubview:self.classIDTextField];
    
    [self.classIDTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        if(self.deploySegment) {
            make.top.equalTo(self.deploySegment.bjl_bottom).offset(20.f);
        }
        else {
            make.top.equalTo(self.contentView).offset(50.f);
        }
        make.left.equalTo(self.view).offset(30.f);
        make.right.equalTo(self.view).offset(-30.f);
        make.height.equalTo(@35);
    }];
}

- (void)setupSessionIDTextField {
    NSString *sessionString = @"201812251";
    self.sessionIDTextField = [self textFieldwithContent:sessionString leftLabelText:@"sessionId:"];
    [self.contentView addSubview:self.sessionIDTextField];
    [self.sessionIDTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.classIDTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setuptokenTextField {
    NSString *token = @"YBNpl56vh_n6GBtNSJkwA6Bm9iXSfd0pI5Z19POKRiip3A5MMO7adA";
    self.tokenTextField = [self textFieldwithContent:token leftLabelText:@"token: "];
    
    [self.contentView addSubview:self.tokenTextField];
    [self.tokenTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.sessionIDTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setupUserInfoTextField {
    NSString *userName = @"李四-正式环境";
    self.userInfoTextField = [self textFieldwithContent:userName leftLabelText:@"userName: "];
    [self.contentView addSubview:self.userInfoTextField];
    
    [self.userInfoTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.tokenTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setupUserNumberTextField {
    NSString *userNo = @"123456";
    self.userNumaberTextField = [self textFieldwithContent:userNo leftLabelText:@"userNumber: "];
    [self.contentView addSubview:self.userNumaberTextField];
    [self.userNumaberTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.userInfoTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setupClipedVersionTextField {
    self.clipedVersionTextField = [self textFieldwithContent:@"" leftLabelText:@"clipedVer: "];
    self.clipedVersionTextField.placeholder = @"请输入裁剪版本";
    [self.contentView addSubview:self.clipedVersionTextField];
    [self.clipedVersionTextField bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.userNumaberTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setupVideoUrlTextField {
    self.videoUrlTextField = [self textFieldwithContent:@"" leftLabelText:@"回放链接："];
    
    self.videoUrlTextField.text = @"https://b41558528.at.baijiayun.com/web/playback/index?classid=20061060970420&session_id=202006100&token=rYLf7UDngM0HxEx6eiI8M3ylyXZXTqeLbQXSXD8olUkBqeOy5yr93O7USVkkWntwAvwtL1D_xZIKp0fXMnVKLQ";
    self.videoUrlTextField.text = @"https://b41558528.at.baijiayun.com/web/playback/index?classid=20062383973423&session_id=202006230&version=1&token=cBz7-dqF_W8HxEx6eiI8M0RfTBJlOYGoVmc3iEDN8yoDxfqCS-AsIu7USVkkWntw-kUhBOGMyYMKp0fXMnVKLQ";
    
    self.videoUrlTextField.clipsToBounds = YES;
    self.videoUrlTextField.rightViewMode = UITextFieldViewModeAlways;
    self.videoUrlTextField.leftViewMode = UITextFieldViewModeAlways;
    UIButton *rightBtn = [UIButton new];
    rightBtn.backgroundColor = [UIColor blueColor];
    [rightBtn setTitle:@"Done" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(parseVideoUrl) forControlEvents:UIControlEventTouchUpInside];
    self.videoUrlTextField.rightView = rightBtn;
    
    UIButton *leftBtn = [UIButton new];
    leftBtn.backgroundColor = [UIColor redColor];
    [leftBtn setTitle:@"clear" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(clearText) forControlEvents:UIControlEventTouchUpInside];
    self.videoUrlTextField.leftView = leftBtn;
    
    [self.contentView addSubview:self.videoUrlTextField];
    [self.videoUrlTextField bjl_makeConstraints:^(BJLConstraintMaker * _Nonnull make) {
        make.top.equalTo(self.clipedVersionTextField.bjl_bottom).offset(20.f);
        make.left.right.height.equalTo(self.classIDTextField);
    }];
}

- (void)setupButton {
    UIButton *avPlayerBtn = [self playButtonWithTitle:@"AVPlayer 播放"];
    [avPlayerBtn addTarget:self action:@selector(enterRoomWithAVPlayer) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:avPlayerBtn];
    [avPlayerBtn bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(self.videoUrlTextField.bjl_bottom).offset(30);
        make.height.equalTo(@35);
        make.width.equalTo(@160);
        make.centerX.equalTo(self.view);
    }];
    
    UIButton *ijkPlayerBtn = [self playButtonWithTitle:@"IJKPlayer 播放"];
    [ijkPlayerBtn addTarget:self action:@selector(enterRoomWithIJKPlayer) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:ijkPlayerBtn];
    [ijkPlayerBtn bjl_makeConstraints:^(BJLConstraintMaker *make) {
        make.top.equalTo(avPlayerBtn.bjl_bottom).offset(30);
        make.height.equalTo(@35);
        make.width.equalTo(@160);
        make.centerX.equalTo(self.view);
    }];
}

- (UIButton *)playButtonWithTitle:(NSString *)title {
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:title forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    button.layer.masksToBounds = YES;
    button.layer.cornerRadius = 3.0;
    return button;
}

#pragma mark - action

- (void)enterRoomWithAVPlayer {
    [self enterRoomWithPlayerType:BJVPlayerType_AVPlayer];
}

- (void)enterRoomWithIJKPlayer {
    [self enterRoomWithPlayerType:BJVPlayerType_IJKPlayer];
}

- (void)enterRoomWithPlayerType:(BJVPlayerType)playerType {

    BJPPlaybackOptions *playbackOptions = [PUPlayOptionsManager getPlaybackOptions];
    playbackOptions.playerType = playerType;
    
    NSInteger clipedVerion = [self.clipedVersionTextField.text integerValue];
    if (clipedVerion > 0) {
        playbackOptions.clipedVersion = clipedVerion;
    }
    else {
        playbackOptions.clipedVersion = -1;
    }
    
    [PUPlayOptionsManager setPlaybackOptions:playbackOptions];
    BJPRoomViewController *vc = [BJPRoomViewController onlinePlaybackRoomWithClassID:self.classIDTextField.text
                                                                           sessionID:self.sessionIDTextField.text
                                                                               token:self.tokenTextField.text
                                                                           accessKey:nil
                                                                             options:[PUPlayOptionsManager getPlaybackOptions]];
    [self bjl_presentFullScreenViewController:vc animated:YES completion:nil];
}

#pragma mark -

- (void)clearText {
    self.videoUrlTextField.text = @"";
}

- (void)parseVideoUrl {
    [self.view endEditing:YES];
    if (!self.videoUrlTextField.text) {
        return;
    }
    
//    https://b41558528.at.baijiayun.com/web/playback/index?classid=20042450171844&session_id=202004240&token=jBPXYOesdjkHxEx6eiI8M82exoxKGaMYZ079GVwlTCC4MWG0xZvwOyjBTbL__uu33y0gmCdgNeAKp0fXMnVKLQ
//    NSString *query = [self.videoUrlTextField.text componentsSeparatedByString:@"?"].lastObject;
   
    // version=1, 表示该回放为裁剪过的回放视频
//  https://e95896064.at.baijiayun.com/web/playback/index?classid=20061143973302&session_id=202006110&version=1&token=bYk8vNsqXHyJ2LiQbgHVcPcIUZcRjTYy6AsMThC77MK0YP971EYWHmKTSe-VuvcEwcDq2Lrs-80Kp0fXMnVKLQ
    
    NSURL *url = [NSURL URLWithString:self.videoUrlTextField.text];
    NSString *query = url.query;
    NSArray *parameterArray = [query componentsSeparatedByString:@"&"];
    
    self.clipedVersionTextField.text = @"";
    
    self.sessionIDTextField.text = @"";
    for (NSString *para in parameterArray) {
        if ([para hasPrefix:@"classid"]) {
            self.classIDTextField.text = [para componentsSeparatedByString:@"="].lastObject;
        }
        if ([para hasPrefix:@"token"]) {
            self.tokenTextField.text = [para componentsSeparatedByString:@"="].lastObject;
        }
        if ([para hasPrefix:@"session_id"]) {
            self.sessionIDTextField.text = [para componentsSeparatedByString:@"="].lastObject;
        }
        if ([para hasPrefix:@"version"]) {
            self.clipedVersionTextField.text = [para componentsSeparatedByString:@"="].lastObject;
        }
    }
    
    // url.host = b41558528.at.baijiayun.com
    // url.host = latest37429504.test-at.baijiayun.com
    // 设置个性域名
    if ([url.host containsString:@".at."] || [url.host containsString:@"-at."]) {
        NSString *privatePrefixString = [url.host componentsSeparatedByString:@"."].firstObject;
        NSString *privatePrefix = privatePrefixString.length ? privatePrefixString : nil;
        [PUPlayOptionsManager setPrivatePrefix:privatePrefix];
        [[BJVAppConfig sharedInstance] setPrivateDomainPrefix:[PUPlayOptionsManager getPrivatePrefix]];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - private

- (UITextField *)textFieldwithContent:(NSString *)content leftLabelText:(NSString *)text {
    UITextField *textField = [UITextField new];
    textField.layer.borderWidth = 1.f;
    textField.layer.borderColor = [UIColor grayColor].CGColor;
    textField.text = content;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.leftViewMode = UITextFieldViewModeAlways;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 90, 42)];
    label.text = text;
    textField.leftView = label;
    return textField;
}

@end
