//
//  PUAppDelegate.m
//  BJPlayerManagerUI
//
//  Created by oushizishu on 06/02/2017.
//  Copyright (c) 2017 oushizishu. All rights reserved.
//

#import <BJLiveBase/BJL_EXTScope.h>
#import <BJLiveBase/NSObject+BJL_M9Dev.h>
#import <BJLiveBase/UIKit+BJLHandler.h>
#import <BJLiveBase/UIAlertController+BJLAddAction.h>

#import <BJVideoPlayerCore/BJVPlayerManager.h>
#import <BJVideoPlayerCore/BJVideoPlayerCore.h>
#import <BJVideoPlayerCore/BJVRoom.h>
#import <BJVideoPlayerCore/BJVDownloadManager.h>
#import <BJVideoPlayerCore/PMDownloadManager.h>

#if DEBUG
#import <FLEX/FLEXManager.h>
#endif

#import "PUAppDelegate.h"
#import "PUMainViewController.h"
#import "PUPlayOptionsManager.h"

#import "UIViewController+PUUtil.h"
#import "UIWindow+PUMotion.h"

#import "BJVDownloadViewController.h"

@interface PUAppDelegate () <BJVRequestTokenDelegate, BJLDownloadManagerClassDelegate>

@property (nonatomic, assign) UIBackgroundTaskIdentifier bgTask;

@end

@implementation PUAppDelegate

- (instancetype)init {
    self = [super init];
    if (self) {
        self.allowRotation = YES;
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [PUMainViewController loadDeployType];
    [[BJVAppConfig sharedInstance] setPrivateDomainPrefix:[PUPlayOptionsManager getPrivatePrefix]];
    [BJVideoPlayerCore setTokenDelegate:self];
    [BJVDownloadManager setClassDelegate:self];
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    UINavigationController *navi = [[PUMainViewController alloc] bjl_wrapWithLightNavigationController];
    self.window.rootViewController = navi;
    [self.window makeKeyAndVisible];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#if DEBUG
        [self setupDeveloperTools];
#endif
    });
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
    [PMDownloadManager downloadManagerWithRootPath:path];
    return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.x
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window {
    if (!self.allowRotation) {
        return UIInterfaceOrientationMaskLandscape;
    }
    return UIInterfaceOrientationMaskAll;
}

#pragma mark - <BJLDownloadManagerClassDelegate>

- (void)downloadManager:(BJVDownloadManager *)downloadManager
URLSessionConfiguration:(NSURLSessionConfiguration *)configuration {
#if DEBUG
    // test change configuration, #see `refreshURLSessionWithCompletion:` in `BJVDownloadViewController.m`
    static BOOL allowsCellularAccess = YES;
    configuration.allowsCellularAccess = allowsCellularAccess; // The default value is YES.
    allowsCellularAccess = !allowsCellularAccess;
#endif
    // configuration.HTTPMaximumConnectionsPerHost = 4; // The default value is 6 in macOS, or 4 in iOS.
}

#pragma mark - DeveloperTools

#if DEBUG

- (void)setupDeveloperTools {
    // [FLEXManager sharedManager].networkDebuggingEnabled = YES;
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self
                           selector:@selector(didShakeWithNotification:)
                               name:UIEventSubtypeMotionShakeNotification
                             object:nil];
}

- (void)didShakeWithNotification:(NSNotification *)notification {
    UIEventSubtypeMotionShakeState shakeState = [notification.userInfo bjl_integerForKey:UIEventSubtypeMotionShakeStateKey defaultValue:UIEventSubtypeMotionShakeStateCancelled];
    if (shakeState == UIEventSubtypeMotionShakeStateEnded) {
        [self showDeveloperTools];
    }
}

- (void)showDeveloperTools {
    UIAlertController *alertController = [UIAlertController
                                          alertControllerWithTitle:@"Developer Tools"
                                          message:nil
                                          preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"FLEX"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action)
                                {
                                    [[FLEXManager sharedManager] showExplorer];
                                }]];

    [alertController addAction:[UIAlertAction actionWithTitle:@"取消"
                                                        style:UIAlertActionStyleCancel
                                                      handler:nil]];
    alertController.popoverPresentationController.sourceView = self.window;
    alertController.popoverPresentationController.sourceRect = [UIApplication sharedApplication].statusBarFrame;
    alertController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionUp | UIPopoverArrowDirectionDown;
    [[UIViewController topViewController] presentViewController:alertController
                                                       animated:YES
                                                     completion:nil];
}

#endif

#pragma mark - <BJVRequestTokenDelegate>

- (void)requestTokenWithVideoID:(NSString *)videoID
                     completion:(void (^)(NSString * _Nullable token, NSError * _Nullable error))completion {
    NSString *key = videoID ?: @"";
    
    completion(BJLDownloadVideoTokens()[key], nil);
    
    // [self requestTokenWithKey:key completion:completion];
}

- (void)requestTokenWithClassID:(NSString *)classID
                      sessionID:(nullable NSString *)sessionID
                     completion:(void (^)(NSString * _Nullable token, NSError * _Nullable error))completion {
    NSString *separator = sessionID.length ? @"-" : @"";
    NSString *key = [NSString stringWithFormat:@"%@%@%@", classID ?: @"", separator, sessionID ?: @""];
    
    completion(BJLDownloadPlaybackTokens()[key], nil);
    
    // [self requestTokenWithKey:key completion:completion];
}

- (void)requestTokenWithKey:(NSString *)key completion:(void (^)(NSString * _Nullable token, NSError * _Nullable error))completion {
    NSDictionary *videos = BJLDownloadVideoTokens();
    NSDictionary *playbacks = BJLDownloadPlaybackTokens();
    NSString *token = videos[key] ?: playbacks[key];
    
    UIAlertController *alert = [UIAlertController
                                alertControllerWithTitle:[NSString stringWithFormat:@"requtst token for %@", key]
                                message:token
                                preferredStyle:UIAlertControllerStyleAlert];
    
    [alert bjl_addActionWithTitle:@"success" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completion(token, nil);
    }];
    
    [alert bjl_addActionWithTitle:@"failure" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completion(nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil]);
    }];
    
    [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
}

@end
