//
//  AppDelegate.m
//  quwanyouxi
//
//  Created by 0280106PC0119 on 2017/2/4.
//  Copyright © 2017年 quicksdk. All rights reserved.
//

#import "AppDelegate.h"
#import <QKN5GameSDK/QKN5GameSDK.h>
#import <SMPCQuickSDK/SMPCQuickSDK.h>

@interface AppDelegate ()
@property (nonatomic, assign) UIInterfaceOrientationMask supportInterface;/** 1竖屏2横屏3全部4左横屏5右横屏 */
@property (nonatomic, unsafe_unretained) UIBackgroundTaskIdentifier backgroundUpdateTask;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) int count;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [NSThread sleepForTimeInterval:2.0];
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"ViewController" bundle:[NSBundle mainBundle]];
    self.viewController = [storyBoard instantiateViewControllerWithIdentifier:@"ViewControllerId"];
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    _window.backgroundColor = [UIColor whiteColor];
    [_window setRootViewController:self.viewController];
    [_window makeKeyAndVisible];
    [[QKN5GameHolder sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    [[QKN5GameHolder sharedInstance] applicationWillResignActive:application];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
//    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    [[QKN5GameHolder sharedInstance] applicationDidEnterBackground:application];
    [self beingBackgroundUpdateTask];
}
-(void)beingBackgroundUpdateTask {
    NSLog(@"QKLog:beingBackgroundUpdateTask");
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];//如果在规定时间内任务没有完成，会调用这个方法。
    }];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(go:) userInfo:nil repeats:YES];
    _count = 0;
}
-(void)go:(NSTimer *)tim {
    _count++;
    if (_count%10 == 0 || [UIApplication sharedApplication].backgroundTimeRemaining == 0) {
        NSLog(@"QKLog:backgroundUpdateTaskrun%d", _count);
    }
}
- (void)endBackgroundUpdateTask {
    NSLog(@"QKLog:endBackgroundUpdateTask");
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    _backgroundUpdateTask = UIBackgroundTaskInvalid;
//    _count = 0;
//    dispatch_queue_t mainQueue = dispatch_get_main_queue();
//    AppDelegate *weakSelf = self;
//    dispatch_async(mainQueue, ^(void) {
//        AppDelegate *strongSelf = weakSelf;
//        if (strongSelf != nil){
//          // 销毁后台任务标识符
//            strongSelf.backgroundUpdateTask = UIBackgroundTaskInvalid;
//        }
//  });
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [[QKN5GameHolder sharedInstance] applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[QKN5GameHolder sharedInstance] applicationDidBecomeActive:application];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    [[QKN5GameHolder sharedInstance] applicationWillTerminate:application];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [[QKN5GameHolder sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [[QKN5GameHolder sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[QKN5GameHolder sharedInstance] application:application didReceiveRemoteNotification:userInfo];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    [[QKN5GameHolder sharedInstance] application:application handleOpenURL:url];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(nullable NSString *)sourceApplication annotation:(id)annotation
{
    [[QKN5GameHolder sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    return YES;
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
    [[QKN5GameHolder sharedInstance] application:app openURL:url options:options];
    return YES;
}
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    [[SMPCQuickSDK defaultInstance]application:application continueUserActivity:userActivity restorationHandler:restorationHandler];
    return YES;
}
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window
{
    [[QKN5GameHolder sharedInstance] application:application supportedInterfaceOrientationsForWindow:window];
    if([SMPCQuickSDK defaultInstance].channelType == 39 || [SMPCQuickSDK defaultInstance].channelType == 1803){
        //39是XY渠道号，XY要求控制方向
        return [[SMPCQuickSDK defaultInstance] application:application supportedInterfaceOrientationsForWindow:window];
    }else{
        [[SMPCQuickSDK defaultInstance] application:application supportedInterfaceOrientationsForWindow:window];
    }
    return self.supportInterface;
}
#pragma mark - getter
- (UIInterfaceOrientationMask)supportInterface {
    if (!_supportInterface) {
        NSDictionary * infoDict = [NSBundle mainBundle].infoDictionary;
        NSArray * interfaceArr = [infoDict objectForKey:@"UISupportedInterfaceOrientations"];
        if ([interfaceArr containsObject:@"UIInterfaceOrientationPortrait"]) {
            _supportInterface = UIInterfaceOrientationMaskPortrait;
            if ([interfaceArr containsObject:@"UIInterfaceOrientationLandscapeLeft"]||[interfaceArr containsObject:@"UIInterfaceOrientationLandscapeRight"]) {
                _supportInterface = UIInterfaceOrientationMaskAll;
            }
        } else {
            if (interfaceArr.count == 2) {
                _supportInterface = UIInterfaceOrientationMaskLandscape;
            }
            else if (interfaceArr.count == 1) {
                if ([interfaceArr.firstObject isEqualToString:@"UIInterfaceOrientationLandscapeLeft"]) {
                    _supportInterface = UIInterfaceOrientationMaskLandscapeLeft;
                } else {
                    _supportInterface = UIInterfaceOrientationMaskLandscapeRight;
                }
            }
        }
    }
    return _supportInterface;
}
@end
