//
//  AppDelegate.m
//  OffcnIMSDKiOS
//
//  Created by vockey on 2018/7/25.
//  Copyright © 2018年 中公教育. All rights reserved.
//

#import "AppDelegate.h"
#import "ViewController.h"
#import "OffcnIMSDKiOS.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UINavigationController *mainVC = [[UINavigationController alloc] initWithRootViewController:[[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateInitialViewController]];
    
    mainVC.navigationBar.translucent = NO;
    self.window.rootViewController = mainVC;
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    
    //中公直播使用测试环境设置为YES，正式环境设置为NO或者去掉这个配置
    NSNumber *changeEnvironment = [[NSUserDefaults standardUserDefaults] valueForKey:kOffcnIMSDKiOS_changeEnvironment];
    NSLog(@"changeEnvironment---%@",changeEnvironment);
    [OffcnIMSDKiOS defaultService].isTest = [changeEnvironment boolValue];
    
    //获取网络状态和内部初始化处理
    [[OffcnIMSDKiOS defaultService] startNotifierUseRealReachability];
    
    //推送
    [self registerOffcnUserNotificationSettingsWithApplication:application options:launchOptions];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (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.
}


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


- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)(void))completionHandler{

}

-(void)registerOffcnUserNotificationSettingsWithApplication:(UIApplication *)application options:(NSDictionary *)launchOptions{
    //    application.applicationIconBadgeNumber = 0;
    
    if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0){
        // 1.请求授权可以给用户发送通知
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert categories:nil];
        
        [application registerUserNotificationSettings:settings];
    }else{
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound];
    }
    
    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]){
        // 跳转
    }
}

/**
 *  远程推送注册成功
 *
 *  @param deviceToken deviceToken
 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    // 25bb75ac 3ffcebd7 90d9f517 1ebca904 154a367a 87781e5d b9ea288e 37fdf487
    NSLog(@"-----deviceToken ---- ---- %@ devDesc ---%@", deviceToken,deviceToken.description);
    
    NSString *str = [self hexStringForData:deviceToken];
    [OffcnIMSDKiOS defaultService].deviceToken = str;
    NSLog(@"token--- %@",str);
    //注册成功，返回token
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"APNS返回的Token:" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    //    applicationIconBadgeNumber
}
-(NSString *)hexStringForData:(NSData *)data{

    if (data == nil) {
        return nil;
    }

    NSMutableString *hexString = [NSMutableString string];
    const unsigned char *p = [data bytes];
    for (int i=0; i < [data length]; i++) {
        [hexString appendFormat:@"%02x", *p++];
    }
    return hexString;
}

/**
 *  注册失败
 *
 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    NSLog(@"注册失败 ---- %@",error);
    NSString *tokenStr = [NSString stringWithFormat:@"%@",error];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"注册失败!" message:tokenStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    NSLog(@"注册失败%@",error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSLog(@"接收到远程推送通知 ---- %@", userInfo);
    
    /*
     
     "name" : "YFPushTest",
     "action_type" : "1",
     "message" : "您的车辆京KKKKKK于2016-4-22 驶入邯郸",
     "aps" : {
        "alert" : "This is some fancy message.",
        "badge" : 1,
        "sound" :  "您的车辆京KKKKKK于2016-4-22 驶入邯郸"
     };
     
     */
    
    //    application.applicationIconBadgeNumber -=1;
    //将推送消息以alert形式呈现
    NSString *message = [[userInfo objectForKey:@"aps"]objectForKey:@"alert"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
    
    
    UILocalNotification *backgroudMsg = [[UILocalNotification alloc] init];
    if (backgroudMsg) {
        backgroudMsg.timeZone = [NSTimeZone defaultTimeZone];
        backgroudMsg.alertBody = @"VoIP来电";
        backgroudMsg.alertAction = @"查看";
        NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
        backgroudMsg.userInfo = infoDic;
        [[UIApplication sharedApplication] presentLocalNotificationNow:backgroudMsg];
        //[self cerateAVAudioPlayer];
    }
}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    NSLog(@"接收到本地推送通知 ---- %@", notification.userInfo);
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
    
    NSLog(@"ls---- %@",notificationSettings);
    
    // 2.注册远程通知
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void(^)(void))completionHandler{
    
    NSLog(@"ios9新增 --- %@ -- %@ --- %@",identifier,userInfo,responseInfo);
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)(void))completionHandler{
    
    NSLog(@"ios8新增 --- %@ -- %@ --- %@",identifier,userInfo,application);
}

@end
