//
//  ICRAppDelegate.m
//  XFFruit
//
//  Created by Xummer on 3/23/15.
//  Copyright (c) 2015 Xummer. All rights reserved.
//

#import "ICRAppDelegate.h"
#import "ICRAppViewControllerManager.h"
#import "ICRURLProtocol.h"
#import "BMKMapManager.h"
#import "ICRHTTPController.h"
#import "APService.h"

@interface ICRAppDelegate ()
@property (strong, nonatomic) BMKMapManager *mapManager;
@property (strong, nonatomic) NSString *version;//本地版本号
@property (strong, nonatomic) NSString *severVersion;//服务器版本号
@property (strong, nonatomic) NSString *intVersion;//本地版本号
@property (strong, nonatomic) NSString *intSeverVersion;//服务器版本号

@property (strong, nonatomic) NSString *severUrl;//Ipa下载地址
@property (assign, nonatomic) BOOL severForceUpdate;//强制更新

@end

@implementation ICRAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyWindow];
    
    [NSURLProtocol registerClass:[ICRURLProtocol class]];
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
    CLog(@"%@",path);
    
    [self enterpriseUpdate];

    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //categories
        [APService
         registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                             UIUserNotificationTypeSound |
                                             UIUserNotificationTypeAlert)
         categories:nil];
    } else {
        //categories nil
        [APService
         registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                             UIRemoteNotificationTypeSound |
                                             UIRemoteNotificationTypeAlert)
#else
         //categories nil
         categories:nil];
        [APService
         registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                             UIRemoteNotificationTypeSound |
                                             UIRemoteNotificationTypeAlert)
#endif
         // Required
         categories:nil];
    }
    [APService setupWithOption:launchOptions];
    [self setupBMKMapMgr];
    _m_appViewControllerMgr = [ICRAppViewControllerManager getAppViewControllerManager];
#pragma 版本更新
    [self.window makeKeyAndVisible];
    return YES;
}
#pragma mark enterprise alertView 企业版提示
- (void)enterpriseUpdate{
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"Info" ofType:@"plist"];
    NSDictionary* content =[NSDictionary dictionaryWithContentsOfFile:path];
    NSString *version = [content valueForKey:@"CFBundleVersion"] ;
    self.version=version;
    
    // 获取服务器更新信息
    [ self  getDataFromServer];
    
}
//请求服务器更新信息
- (void)getDataFromServer{
    __weak typeof(self)weakSelf = self;
    void(^succ)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (data) {
            NSInteger success = [data[@"success"] integerValue];
            NSString *message  = data[@"message"] ;
            if (success == 1) {
                
                NSDictionary *dictData = data[@"data"];
                NSString*serverVeision=[dictData objectForKey:@"version"];
                NSString*serverUrl=[dictData objectForKey:@"url"];
                BOOL forceUpdate= [dictData objectForKey:@"forceUpdate"];
                self.severVersion=serverVeision;
                self.severUrl=serverUrl;
                self.severForceUpdate=forceUpdate;
                [strongSelf  comperVersion];
            }else{
                [IBTLoadingView showTips:message];
            }
        }else{
            [IBTLoadingView showTips:@"     无记录     "];
        }
    };
    void(^fail)(id) = ^(id data) {
        [IBTLoadingView hideHUDWithText:nil];
        [IBTLoadingView showTips:data];
    };
    [IBTLoadingView showProgressLabel:@"正在加载..."];
    [[ICRHTTPController sharedController] getVeisionIdWithType:@"ipa" success:succ failure:fail];
}
//比较版本号及是否下载
-(void)comperVersion
{
    if (self.version && self.severVersion) {
        self.intVersion=@"";
        self.intSeverVersion=@"";
        NSArray *array1 = [self.version componentsSeparatedByString:@"."];
         NSArray *array2 = [self.severVersion componentsSeparatedByString:@"."];
        for (int i = 0; i < [array1 count]; i++) {
            self.intVersion=[self.intVersion stringByAppendingFormat:@"%@",[array1 objectAtIndex:i]];
            NSLog(@"string:%@", [array1 objectAtIndex:i]);
        }
        for (int i = 0; i < [array2 count]; i++) {
            self.intSeverVersion=[self.intSeverVersion stringByAppendingFormat:@"%@",[array2 objectAtIndex:i]];
            NSLog(@"string:%@", [array2 objectAtIndex:i]);
        }
        BOOL isNeedUpdate=[self compareVersion];
//        NSComparisonResult comResult = [self p_compareVersions: self.version betweenVersion2:self.severVersion];
        
        if (isNeedUpdate) {
            if (self.severForceUpdate) {
                //强制更新
//                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message:  @"有新版本发布请您下载最新版本" delegate:self cancelButtonTitle:nil otherButtonTitles: @"去下载", nil];
//                alertV.tag = 1001;
//                [alertV show];
            }else
            {
                UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"新版本告知" message:  @"有新版本发布请您下载最新版本" delegate:self cancelButtonTitle:@"下次再说"otherButtonTitles: @"去下载", nil];//
                alertV.tag = 1002;
                [alertV show];
            }
        }
    }
}
-(BOOL)compareVersion
{
    float  version=[self.intVersion floatValue];
    float severVersion=[self.intSeverVersion floatValue];
    if (severVersion >version) {
        return YES;
    }else
    {
        return NO;
    }
}
- (void) alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==1001) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.severUrl]];
    }else if (alertView.tag==1002)
    {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.severUrl]];
        }
    }
    
}
//比较版本号
- (NSComparisonResult)p_compareVersions: (NSString *)version1 betweenVersion2: (NSString *)version2{
    NSComparisonResult result = NSOrderedSame;
    if ([version2 isEqualToString:@""]) {
        result = NSOrderedDescending;
        return result ;
    }
    
    NSMutableArray *a = (NSMutableArray *)[version1 componentsSeparatedByString:@"."];
    NSMutableArray *b = (NSMutableArray *)[version2 componentsSeparatedByString:@"."];
    
    while (a.count < b.count) {[ a addObject:@"0"];}
    while (b.count < a.count) {[ b addObject:@"0"];}
    
    for(int i = 0; i < a.count; ++i){
        if ([[a objectAtIndex:i] integerValue] < [[b objectAtIndex:i] integerValue]) {
            result = NSOrderedAscending;
            break;
        }else if ([[b objectAtIndex:i] integerValue] < [[a objectAtIndex:i] integerValue]){
            result = NSOrderedDescending;
            break;
        }
    }
    return  result;
    
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    CLog (@"%@", [NSString stringWithFormat:@"Device Token: %@", deviceToken]);
    [APService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required
    [APService handleRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼￼
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

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

#pragma mark - Private
- (void)setupBMKMapMgr {
    self.mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [_mapManager start:BMK_ID generalDelegate:nil];
    if (!ret) {
        CLog(@"mapManager start failed!");
    }
}

@end
