#import "AppDelegate+indigitall.h"
#import <objc/runtime.h>

#import "CDVIndigitall.h"
#import "CDVINDefaults.h"
#import <Indigitall/Indigitall.h>
#import <UserNotifications/UserNotifications.h>

@implementation CDVAppDelegate (indigitall)


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions {
    
    // No pises a otros si ya hay delegate
    UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;
    if (center.delegate == nil) {
        center.delegate = (id<UNUserNotificationCenterDelegate>)self;
    }

    return true;
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [CDVIndigitall.cdvIndigitallPlugin sendToken:deviceToken];
    [Indigitall setDeviceToken:deviceToken onNewUserRegistered:^(INDevice * _Nonnull device) {
        NSLog(@"NewUserRegistered:%@", device.pushToken);
    }];
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {

    [CDVIndigitall.cdvIndigitallPlugin sendNotification:notification.request.content.userInfo];
    completionHandler([Indigitall willPresentNotification]);
}

- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler {

    NSMutableDictionary *dict = [response.notification.request.content.userInfo[@"data"] mutableCopy];
    NSMutableDictionary *data = [dict mutableCopy];

    if (data != nil && data[@"action"] != nil) {
        NSMutableDictionary *action = [data[@"action"] mutableCopy];
        
        [action setValue:response.actionIdentifier forKey:@"clickedButton"];
        data[@"action"] = action;
        dict[@"data"] = data;
    }

    NSDictionary *payload = [dict copy];

    [CDVIndigitall.cdvIndigitallPlugin onHandleNotificationTap:payload];

    [Indigitall handleWithResponse:response withCompletionHandler:^(INPush * _Nonnull push, INPushAction * _Nonnull action) {
        [CDVINDefaults setIndigitallHandleWithNotificationPush:payload];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"IndigitallHandleWithNotificationPush"
                                                                object:payload];
        });
        
        completionHandler();
    }];
}

@end
