//
//  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"
#import "RequestHandler.h"
#import "DeviceModel.h"

#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.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;
    [application cancelAllLocalNotifications];
    
    
    [self initializeApp];
    [self initRemoteNotification:launchOptions];
    
	return YES;
}

#pragma mark Handlers

- (void)initializeApp {
    
    [Fabric with:@[[Crashlytics class]]];
    //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 fromFinishLaunching:YES];
        }
    }
}


// 디바이스 토큰 받는곳
- (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{

    NSLog(@"didReceiveRemoteNotification");
    [self handlePushNotification:userInfo fromFinishLaunching:NO];
}

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


- (void)handlePushNotification:(NSDictionary *)pushInfo
           fromFinishLaunching:(BOOL)fromFinishLaunching {
    
    NSLog(@"pushInfo %@", pushInfo);

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    NSString *message = nil;
    NSString *title = nil;
    
    NSString *pushTypeCode = [pushInfo objectForKey:@"push_noti_type_code"];
    if (pushTypeCode) {
        
        message = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"body"];
        title = [[[pushInfo objectForKey:@"aps"] objectForKey:@"alert"] objectForKey:@"title"];
        
        NSString *homegrpId = [pushInfo objectForKey:@"homegrp_id"];
        
        [self handleWithPushTypeCode:pushTypeCode
                           dummyCode:homegrpId
                             message:message
                               title:title
                 fromFinishLaunching:fromFinishLaunching];
        
        return;
    }
    else {

        message = [[pushInfo objectForKey:@"aps"] objectForKey:@"alert"];
    }
    
    
    if (message && [message isKindOfClass:NSString.class] && [message isEmptyString]) {
        [[JDFacade facade] alert:message];
    }
}


- (void)handleWithPushTypeCode:(NSString *)pushTypeCode
                     dummyCode:(NSString *)dummyCode
                       message:(NSString *)message
                         title:(NSString*)title
           fromFinishLaunching:(BOOL)fromFinishLaunching {
    
    NSLog(@"%s\n %@, %@, %@", __PRETTY_FUNCTION__, pushTypeCode, dummyCode, message);
    
    if ([pushTypeCode isEqualToString:@"HOME_MEM_INV"]) {//홈 초대받음
        [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [[JDFacade facade] loadInvitationView];
            }
        }];
        
    } else if ([pushTypeCode isEqualToString:@"HOME_MEM_REF"]) {//홈초대 거절 시
        [[JDFacade facade] alert:message];
        [[JDFacade facade] updateMainViewController];
        
    }
//    else if ([pushTypeCode isEqualToString:@"HOME_MEM_BAN"]) {//홈에서 강퇴됨
//        [[JDFacade facade] alert:message completionHander:^{
//            [[JDFacade facade] updateMainViewController];
//            [[JDFacade facade] requestPollingHomeHubStatus:nil];
//        }];
//        
//    }
    else if ([pushTypeCode isEqualToString:@"HOME_MEM_SEL"]) {//홈에서 멤버가 탈퇴함
        [[JDFacade facade] alert:message];
        [[JDFacade facade] updateMainViewController];
        
    } else  if ([pushTypeCode isEqualToString:@"HOME_DEL"]) {//홈그룹 삭제
        [[JDFacade facade] alert:message completionHander:^{
            [[JDFacade facade] requestPollingHomeHubStatus:nil];
        }];
        
    } else if ([pushTypeCode isEqualToString:@"DVC_CER_REV"]) {//단말 인증 해지됨
        [[JDFacade facade] alert:message completionHander:^{
            [[JDFacade facade] logout];
        }];
        
    } else if ([pushTypeCode isEqualToString:@"MODE_CHG"] || [pushTypeCode isEqualToString:@"MODE_CHG_ERR"]) {//홈 모드 변경 시, 홈 모드 변경 시 일부장치 제어 실패
        [[JDFacade facade] alert:message];
        
    } else if ([pushTypeCode isEqualToString:@"RULE_EXC"] || [pushTypeCode isEqualToString:@"RULE_ERR"]) {//규칙 실행 시, 규칙 실패 누적으로 규칙
        
        [[JDFacade facade] alert:message];
        
    } else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"DVC_OWN_CHG"]) {//홈허브 삭제됨, 장치 소유주 변경 알림 - 대시보드
        [[JDFacade facade] alert:message completionHander:^{
            [[JDFacade facade] requestPollingHomeHubStatus:^{
                [[JDFacade facade] dismissModalStack:YES completion:nil];
            }];
        }];
        
    } else if ([pushTypeCode isEqualToString:@"MEM_ALL_OUT"]) {//멤버 Any In 시
        
        NSString *path = API_GET_DEVICE_WARN_NODES;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{//RUN to background thread
            DeviceListModel *fdeviceList = [[RequestHandler handler] sendSyncGetRequestAPIPath:path parameters:nil
                                                                            modelClass:[DeviceListModel class] showLoadingView:NO];
            NSMutableString *onDevices, *openDevices;
            if (fdeviceList && fdeviceList.list && fdeviceList.list.count) {
                onDevices = [[NSMutableString alloc] init];
                openDevices = [[NSMutableString alloc] init];
                
                NSArray<DeviceModel> *devices = fdeviceList.list;
                
                for (DeviceModel *device in devices) {
                    NSInteger typeId = [device.cmdclsTypeId integerValue];
                    
                    switch (typeId) {
                        case 17001:
                        case 17002:{//switch
                            NSString *prefix = [onDevices isEmptyString] ? ksEmptyString : @", ";
                            [onDevices appendFormat:@"%@%@", prefix, device.deviceName];
                        }
                            break;
                        default: {//others
                            NSString *prefix = [openDevices isEmptyString] ? ksEmptyString : @", ";
                            [openDevices appendFormat:@"%@%@", prefix, device.deviceName];
                        }
                            break;
                    }
                }
                
                if (![onDevices isEmptyString]) {
                    [onDevices insertString:@"\n켜짐: " atIndex:0];
                }
                
                if (![openDevices isEmptyString]) {
                    [openDevices insertString:@"\n열림: " atIndex:0];
                }
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString *tmpMessage = [NSString stringWithFormat:@"%@\n%@%@", message, onDevices ? onDevices : ksEmptyString, openDevices ? openDevices : ksEmptyString];
                [[JDFacade facade] confirmTitle:@"알림" message:tmpMessage btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 0) {
                        [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
                    }
                }];
            });
        });
        
        
    } else if ([pushTypeCode isEqualToString:@"MEM_ANY_IN"]) {//멤버 All Out 시, 멤버 Any In 시
        [[JDFacade facade] confirmTitle:@"알림" message:message btnOKLabel:@"확인" btnCancelLabel:@"나중에" completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [[JDFacade facade] gotoWishMenu:KNMenuIdThings];
            }
        }];
    }
    //권한양도 받은 경우
    else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD") ) {

        [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
                                                            object:message];
    }
    //보낸 마스터 양도 거절
    else if ( !fromFinishLaunching && EQUALS(pushTypeCode, @"MAS_GRD_REJECT") ) {

        [[JDFacade facade] alertTitle:title message:message];
    }
    //보낸 마스터 양도 완료 || 멤버가 계정 삭제함
    else if ( !fromFinishLaunching &&
             (EQUALS(pushTypeCode, @"MAS_GRD_ACCEPT")||EQUALS(pushTypeCode, @"HOME_MEM_SEL")) ) {

        [[JDFacade facade] alertTitle:title message:message completionHander:^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kMasGradeNoti
                                                                object:nil];
        }];
    }
    //계정 삭제 당함
    else if ( EQUALS(pushTypeCode, @"HOME_MEM_BAN") ) {
        
        [[JDFacade facade] alertTitle:title message:message completionHander:^{
            
            [[JDFacade facade]logout];
        }];
    }
    //타 사용자가 내 번호로 인증받음
    else if ( EQUALS(pushTypeCode, @"MOBILE_NUM_CHG") ) {
        
        [[JDFacade facade] confirmTitle:@"휴대폰 번호 변경"
                                message:message
                             btnOKLabel:@"보기"
                         btnCancelLabel:@"닫기"
                             completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                                 
                                 if (buttonIndex == 0) {
                                     
                                     [[JDFacade facade] loadSettingsNumChangeView];
                                 }
                             }];
    }
    //홈허브 오프라인
    else if ( EQUALS(pushTypeCode, @"HOMEHUB_OFF") ) {
        
        [[JDFacade facade] confirmTitle:@"홈허브 오프라인"
                                message:message
                             btnOKLabel:@"보기"
                         btnCancelLabel:@"닫기"
                             completion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
                                 
                                 if (buttonIndex == 0) {
                                     
                                     [[JDFacade facade] loadHomeHubView];
                                 }
                                 
                             }];
    }
    //
    else if ([pushTypeCode isEqualToString:@"HOMEHUB_DEL"] || [pushTypeCode isEqualToString:@"MODE_CHG"]) {//홈허브 삭제, 홈모드 변경 알림
        
        [[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];
            } else {
                [[JDFacade facade] requestPollingHomeHubStatus:nil];
            }
        }];
    }
}

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

@end
