//
//  AppNotification.m
//  Project
//
//  Created by haibara on 5/25/18.
//

#import "AppNotification.h"
#import <UserNotifications/UserNotifications.h>
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "UserNotificationsManager.h"
#import "MessageListViewController.h"
#import "SalesEntryDetailViewController.h"
#import "Message.h"
#import "AppLocalConfig.h"
#import "Vars.h"
#import "InterceptionManager.h"

@implementation AppNotification

+(void)load{
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        [UserNotificationsManager sharedManager].handler = ^(UNNotificationResponse *response) {
            if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
                NSDictionary *userInfo = response.notification.request.content.userInfo;
                [self handleNotification:userInfo];
            }
        };
    }
}

+ (void)handleNotification:(NSDictionary *)userInfo {
	NSString *adUrlString = userInfo[@"data"][@"absolute_url"];
	UIViewController *this = [CocoaUtils topMostViewController];
	if ([StringUtils isEmpty:adUrlString]) {
		MessageListViewController *messageListViewController = [[MessageListViewController alloc] init];
		Message *message = [[Message alloc] init];
		if ([userInfo[@"aps"][@"alert"] isKindOfClass:[NSDictionary class]]) {
			message.title = userInfo[@"aps"][@"alert"][@"title"];
			message.content = userInfo[@"aps"][@"alert"][@"body"];
		}else if([userInfo[@"aps"][@"alert"] isKindOfClass:[NSString class]]){
			message.title = userInfo[@"aps"][@"alert"];
		}else{
			if (userInfo) {
				[AppLocalConfig sharedInstance].hasUnreadMessage = YES;
			}
			return;
		}
		[AppLocalConfig sharedInstance].hasUnreadMessage = NO;
		message.notificationTime = [[DateFormatUtils ISO_DATETIME_FORMAT] format:[NSDate date]];
		messageListViewController.message = message;
		[this.navigationController pushViewController:messageListViewController animated:YES];
	}else{
		BOOL isHandle = [[InterceptionManager sharedManager] handleUrlString:adUrlString];
		[AppLocalConfig sharedInstance].hasUnreadMessage = NO;
		if (!isHandle) {
			IMWebViewController *webviewController =  [[IMWebViewController alloc] initWithURLString:adUrlString];
			webviewController.hidesBottomBarWhenPushed = YES;
			[this.navigationController pushViewController:webviewController animated:YES];
		}
	}
	[[NSNotificationCenter defaultCenter] postNotificationName:UnreadMessageNotification object:nil];
}


@end
