//
//  AppDelegate.m
//  kneet2
//
//  Created by Created by Jason Lee on 10/1/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "JDObject.h"
#import "AppDelegate.h"

@interface AppDelegate ()

@end

// Constants
// static NSString * const kSomeLocalConstant = @"SomeValue";

@implementation AppDelegate

@synthesize window = _window;

#pragma mark -
#pragma mark Static methods

#pragma mark -
#pragma mark Init and dealloc

#pragma mark -
#pragma mark Properties

#pragma mark -
#pragma mark Public methods

#pragma mark - 
#pragma mark Private methods

#pragma mark - 
#pragma mark Delegate methods

#pragma mark UIApplicationDelegate

- (BOOL)application:(__unused UIApplication *)application didFinishLaunchingWithOptions:(__unused NSDictionary *)launchOptions {
    
#ifndef PRODUCT_MODE //운영모드가 아닐 경우,
    [self checkLaunchOptions:launchOptions];
#endif
    
    application.applicationIconBadgeNumber = 0;
    
    
    [self initializeApp];
    [self initRemoteNotification:launchOptions];
    
	return YES;
}

#pragma mark Handlers

- (void)initializeApp {
    
    //set logger 
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    [[DDTTYLogger sharedInstance] setColorsEnabled:YES];
    
}


#pragma mark - Initialize Application
- (void)checkLaunchOptions:(id)launchOptions {
    
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]) {
        NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey]);
        [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
    }
    
    if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]) {
        NSLog(@"UIApplicationLaunch %@", [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey]);
        [[JDFacade facade] fireLocalNotification:@"UIApplicationLaunchOptionsLocalNotificationKey"];
    }
}


#pragma mark - APNS Setting
/**
 APNS 초기화
 */
- (void)initRemoteNotification:(NSDictionary *)launchOptions {
    // APNS에 디바이스를 등록한다.
#if TARGET_IPHONE_SIMULATOR
    [JDFacade facade].APNSToken = @"IPHONE SIMULATOR";
#else
    UIUserNotificationType types = UIUserNotificationTypeSound | UIUserNotificationTypeBadge | UIUserNotificationTypeAlert;
    UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:notificationSettings];
#endif
    
    if (launchOptions) {
        NSDictionary *pushInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (pushInfo) {
            [self handlePushNotification:pushInfo];
        }
    }
}


// 디바이스 토큰 받는곳
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    NSMutableString *deviceId = [NSMutableString string];
    const unsigned char *ptr = (const unsigned char*) [deviceToken bytes];
    for(int i = 0 ; i < 32 ; i++) {
        [deviceId appendFormat:@"%02x", ptr[i]];
    }
    
    //메모리에 저장.
    [JDFacade facade].APNSToken = deviceId;
    
    NSLog(@"APNS Device Token: %@", deviceId);
}


// 서버에 등록 실패했을 경우.
- (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"didFailToRegisterForRemoteNotifications: %@", error);
}


// 푸시 처리
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    [self handlePushNotification:userInfo];
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    [application registerForRemoteNotifications];
}


- (void)handlePushNotification:(NSDictionary *)pushInfo {
    NSLog(@"%s %@", __PRETTY_FUNCTION__, pushInfo);
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    NSString *message = nil;
//    NSString *pushTypeCode = [pushInfo objectForKey:@"push_type_code"];
//    if (pushTypeCode) {
//        
//        message = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
//        NSString *homegrpId = [pushInfo objectForKey:@"homegrp_id"];
//        [self handleWithPushTypeCode:pushTypeCode dummyCode:homegrpId message:message];
//        
//        return;
//    } else {
//    }
    message = [[pushInfo objectForKey:@"aps"] objectForKey:@"alert"];
    
    if (message && ![message isEmptyString]) {
        [[JDFacade facade] alert:message];
    }
}



#pragma mark - Application Events
- (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.applicationIconBadgeNumber = 0;
}

- (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.
    application.applicationIconBadgeNumber = 0;
    
    NSLog(@"%s\n %zd : 0=active, 1=inactive, 2=background", __PRETTY_FUNCTION__, [UIApplication sharedApplication].applicationState);
    if ([JDFacade facade].loginUser) {//현재 로그인 되있는 경우,
        //초대 내역 갱신.
        
        NSInteger invitationsCount = [[JDFacade facade].loginUser.invitationsCount integerValue];
        [[JDFacade facade] updateLoginInfo:^{//로그인 정보 갱신,
            
            if ([[JDFacade facade].loginUser.invitationsCount integerValue] > invitationsCount) {
                [[JDFacade facade] loadInvitationView];
            }
        }];
    }
}

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

@end
