//
//  AppDelegate+UserNotifications.m
//  Project
//
//  Created by haibara on 5/25/18.
//

#import "AppDelegate+UserNotifications.h"
#import <BlocksKit/NSObject+BKAssociatedObjects.h>
#import <EBBannerView/EBBannerView.h>
#import "Utility.h"
#import "AppNotification.h"
#import "AppLocalConfig.h"

@implementation AppDelegate (UserNotifications)

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

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
	// foreground & background -- ios7~ios9
	application.applicationIconBadgeNumber = 0;
	if (application.applicationState == UIApplicationStateActive) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(performNotificationForEBBannerViewDidClick) name:EBBannerViewDidClickNotification object:nil];
        });
		self.remoteNotificationUserInfo = userInfo;
        [Utility presentRemoteNotificationInActiveWithPayload:userInfo];
	} else {
		[AppNotification handleNotification:userInfo];
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:UnreadMessageNotification object:nil];
	[AppLocalConfig sharedInstance].hasUnreadMessage = YES;
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
	application.applicationIconBadgeNumber = 0;
}

-(void)performNotificationForEBBannerViewDidClick {
	[AppNotification handleNotification:self.remoteNotificationUserInfo];
}

- (NSDictionary *)remoteNotificationUserInfo {
	return [self bk_associatedValueForKey:@selector(remoteNotificationUserInfo)];
}

- (void)setRemoteNotificationUserInfo:(NSDictionary *)remoteNotificationUserInfo {
	[self bk_associateValue:remoteNotificationUserInfo withKey:@selector(remoteNotificationUserInfo)];
}

@end
