/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import "React/RCTRootView.h"
#import <RNCPushNotificationIOS.h>
#import <AVFoundation/AVFoundation.h>
#import <Firebase.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;// import!!!
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
      if (!error) {
        NSLog(@"request authorization succeeded!");
      }
    }];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
      NSLog(@"%@",settings);
    }];
    [[UIApplication sharedApplication] registerForRemoteNotifications];

  }else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
    UIUserNotificationSettings *uns = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound) categories:nil];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    [[UIApplication sharedApplication] registerUserNotificationSettings:uns];
  } else if (@available(iOS 8.0, *)) {
    UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeBadge);
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
  }

  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

  NSURL *jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"MAAGApp"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];
  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];

  return YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  //Register for push notifications
  //For more info, see: https://developers.intercom.com/v2.0/docs/ios-push-notifications
  [application registerUserNotificationSettings:[UIUserNotificationSettings
                                                 settingsForTypes:(UIUserNotificationTypeBadge
                                                                   | UIUserNotificationTypeSound
                                                                   | UIUserNotificationTypeAlert)
                                                 categories:nil]];
  [application registerForRemoteNotifications];
}


// https://github.com/react-native-community/react-native-google-signin/blob/master/docs/ios-guide.md#modify-your-app-to-respond-to-the-url-scheme-optional
//- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url
//  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation options:(nonnull NSDictionary<NSString *,id> *)options {
////  return
////  [RNGoogleSignin application:application
////                      openURL:url
////            sourceApplication:sourceApplication
////                   annotation:annotation
////   ];
//  return [RNGoogleSignin application:application openURL:url options:options];
//
//}
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
//- (BOOL)application:(UIApplication *)application
//            openURL:(NSURL *)url
//            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
////  return [RNGoogleSignin application:application openURL:url sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey] annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
//  return [RNGoogleSignin application:application openURL:url options:options];
//}
//#endif

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNCPushNotificationIOS didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  if (application.applicationState == UIApplicationStateActive) {
    [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
  }
}

// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}
-(void) userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
  completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound);
}

-(void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
  if( [response.actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier] ){
    NSLog(@"didReceiveNotificationResponse Dismiss Action");
    }
  if( [response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier] ){
    NSLog(@"didReceiveNotificationResponse Default");
    }
  if( [response.actionIdentifier isEqualToString:@"Snooze"] ){
    NSLog(@"didReceiveNotificationResponse Snooze");
    }
  if( [response.actionIdentifier isEqualToString:@"Delete"] ){
    NSLog(@"didReceiveNotificationResponse Delete");
    }
  else {
    NSLog(@"Unknown action");
  }

  if (response.notification.request.content.userInfo) {
    [RNCPushNotificationIOS didReceiveRemoteNotification:response.notification.request.content.userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult)) completionHandler];
  }

  completionHandler();
}
@end

