//
//  AppDelegate.m
//  Macalline
//
//  Created by JianjiYuan on 14-12-1.
//  Copyright (c) 2014年 JianjiYuan. All rights reserved.
//

#import "AppDelegate.h"
#import "GexinPushMgr.h"
#import "RootViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "WGS84TOGCJ02.h"

@interface AppDelegate () < CLLocationManagerDelegate >
{
    CLLocationManager *locationMgr;
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [self setDefaultUserDefaultValues];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    RootViewController *vcRoot = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    self.navRoot = [[BaseNavigationController alloc] initWithRootViewController:vcRoot];
    
    self.window.rootViewController = self.navRoot;
    
    //[self setCustomNavBar];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
//    // [1]:使用APPID/APPKEY/APPSECRENT创建个推实例
    //[[GexinPushMgr getInstance] startSdkWith:kAppId appKey:kAppKey appSecret:kAppSecret];
//    // [2]:注册APNS
    [[GexinPushMgr getInstance] registerRemoteNotification];
    
    // [2-EXT]: 获取启动时收到的APN
    NSDictionary* message = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (message) {
        NSString *payloadMsg = [message objectForKey:@"payload"];
        NSString *record = [NSString stringWithFormat:@"[APN]%@, %@", [NSDate date], payloadMsg];
//        [_viewController logMsg:record];
        DLog(@"didFinishLaunchingWithOptions  %@", record);
        NSDictionary *dictPayload = [NSJSONSerialization JSONObjectWithData:[payloadMsg dataUsingEncoding:NSUTF8StringEncoding]
                                                                    options:NSJSONReadingAllowFragments
                                                                      error:nil];
//        [DataMgr getInstance].remoteNotificationID = dictPayload[@"id"];
    }
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    return YES;
}

- (void)setDefaultUserDefaultValues
{
//    if ([[UIApplication getObjectType:String key:kServerAddress] isEqualToString:@""]) {
//        [UIApplication saveObject:@"192.168.32.140" type:String key:kServerAddress];
//    }
//    if ([[UIApplication getObjectType:String key:kServerPort] isEqualToString:@""]) {
//        [UIApplication saveObject:@"8080" type:String key:kServerPort];
//    }
//    if ([[UIApplication getObjectType:String key:kLocalNotifyShakeEnable] isEqualToString:@""]) {
//        [UIApplication saveObject:@"YES" type:String key:kLocalNotifyShakeEnable];
//    }
//    if ([[UIApplication getObjectType:String key:kLocalNotifySoundEnable] isEqualToString:@""]) {
//        [UIApplication saveObject:@"YES" type:String key:kLocalNotifySoundEnable];
//    }
//    
//    
//    if ([[UIApplication getObjectType:String key:kServerAddress] isEqualToString:@""]) {
//        [UIApplication saveObject:@"bestrun.iplink.com.cn" type:String key:kServerAddress];
//    }
//    if ([[UIApplication getObjectType:String key:kServerPort] isEqualToString:@""]) {
//        [UIApplication saveObject:@"9002" type:String key:kServerPort];
//    }
//    if ([[UIApplication getObjectType:String key:kLocalNotifyShakeEnable] isEqualToString:@""]) {
//        [UIApplication saveObject:@"YES" type:String key:kLocalNotifyShakeEnable];
//    }
//    if ([[UIApplication getObjectType:String key:kLocalNotifySoundEnable] isEqualToString:@""]) {
//        [UIApplication saveObject:@"YES" type:String key:kLocalNotifySoundEnable];
//    }
//
    if ([[UIApplication getObjectType:String key:kServerAddress] isEqualToString:@""]) {
        [UIApplication saveObject:@"219.235.234.227" type:String key:kServerAddress];
    }
    if ([[UIApplication getObjectType:String key:kServerPort] isEqualToString:@""]) {
        [UIApplication saveObject:@"8080" type:String key:kServerPort];
    }
    if ([[UIApplication getObjectType:String key:kLocalNotifyShakeEnable] isEqualToString:@""]) {
        [UIApplication saveObject:@"YES" type:String key:kLocalNotifyShakeEnable];
    }
    if ([[UIApplication getObjectType:String key:kLocalNotifySoundEnable] isEqualToString:@""]) {
        [UIApplication saveObject:@"YES" type:String key:kLocalNotifySoundEnable];
    }
}

- (void)setCustomNavBar
{
#if kIOSVersion7Later
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
#endif
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           [UIColor whiteColor], UITextAttributeTextColor,
                                                           [UIFont boldSystemFontOfSize:19], NSFontAttributeName, nil]];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >=7.0) {
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavBar/nav_bar_128.png"]
                                           forBarMetrics:UIBarMetricsDefault];
    }else{
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavBar/nav_bar_88.png"]
                                           forBarMetrics:UIBarMetricsDefault];
    }

}

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

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

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userinfo
{
    [[GexinPushMgr getInstance] didReceiveRemoteNotification:userinfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    [[GexinPushMgr getInstance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // [EXT] 切后台关闭SDK，让SDK第一时间断线，让个推先用APN推送
//    [[GexinPushMgr getInstance] applicationDidEnterBackground];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // [EXT] 切后前台
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // [EXT] 重新上线
//    [[GexinPushMgr getInstance] applicationDidBecomeActive];
    [self checkGPS];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationEndEdit object:nil userInfo:nil];
}

- (BOOL)checkGPS
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status != kCLAuthorizationStatusAuthorized && status != kCLAuthorizationStatusNotDetermined) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"您的GPS功能没有打开，会影响程序使用，请到设置->隐私->定位服务打开." delegate:nil tag:0 cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        return NO;
    }else {
        if(!locationMgr)
            locationMgr = [[CLLocationManager alloc] init];
        locationMgr.delegate = self;
        locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
        locationMgr.distanceFilter = 1;
        [locationMgr startUpdatingLocation];
        
        return YES;
    }
}

#pragma mark
#pragma CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
		   fromLocation:(CLLocation *)oldLocation
{
    
    CLLocationCoordinate2D coord = newLocation.coordinate;
    if (![WGS84TOGCJ02 isLocationOutOfChina:[newLocation coordinate]]) {
        //转换后的coord
        coord = [WGS84TOGCJ02 transformFromWGSToGCJ:[newLocation coordinate]];
    }
    
    //process
    [DataMgr getInstance].location = [NSString stringWithFormat:@"%.6f,%.6f", coord.latitude,
                                      coord.longitude];
    DLog(@"[DataMgr getInstance].location  %@", [DataMgr getInstance].location);
    
    //创建位置
    CLLocation *c = [[CLLocation alloc] initWithLatitude:coord.latitude
                                               longitude:coord.longitude];
    //反向地理编码
    CLGeocoder *revGeo = [[CLGeocoder alloc] init];
    [revGeo reverseGeocodeLocation:c
                 completionHandler:^(NSArray *placemarks, NSError *error) {
                     if (!error && [placemarks count] > 0) {
//                         DLog(@"placemarks %@", placemarks);
                         
                         NSDictionary *dict = [[placemarks objectAtIndex:0] addressDictionary];
                         
                         DLog(@"street address: %@ %@", dict, [dict objectForKey:@"Name"]);
                         [DataMgr getInstance].locationName = dict[@"Name"];
                         
                         [manager stopUpdatingLocation];
                         
                     }else {
                         DLog(@"ERROR: %@", error);
                     }
                 }];
    
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == 1) {
        [UIApplication showAlertViewWithTitle:@"警告" message:@"您的GPS功能没有打开，会影响程序使用，请到设置->隐私->定位服务打开." delegate:nil tag:0 cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
    }
}

@end
