import UIKit
import Flutter
import flutter_local_notifications
import Firebase
import FirebaseMessaging
import UserNotifications
import AppTrackingTransparency

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    
    var firebaseToken : String = "";
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        
        let controller = window.rootViewController as! FlutterViewController
        
        FlutterMethodChannelUtil.handlerMethodChannel(controller: controller)
        
        FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
            GeneratedPluginRegistrant.register(with: registry)
        }
        
        if #available(iOS 10.0, *) {
            UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
        }
        Messaging.messaging().delegate = self;
        FirebaseApp.configure()
        UNUserNotificationCenter.current().delegate=self
        GeneratedPluginRegistrant.register(with: self)
        Messaging.messaging().isAutoInitEnabled = true;
        if #available(iOS 10.0, *) {
                   let center  = UNUserNotificationCenter.current()
                   let content = UNMutableNotificationContent()
                    content.sound = UNNotificationSound.default
                   center.delegate = self
                    UNUserNotificationCenter.current().delegate = self
                    center.requestAuthorization(options: [.sound, .alert, .badge])
         { (granted, error) in
                       if error == nil{
                           DispatchQueue.main.async {
                               UIApplication.shared.registerForRemoteNotifications()
                           }
                       }
                   }

               } else {

                   let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                   UIApplication.shared.registerUserNotificationSettings(settings)
                   UIApplication.shared.registerForRemoteNotifications()
               }
        application.registerForRemoteNotifications()
        
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }


    func requestDataPermission() {
        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                switch status {
                case .authorized:
                    // Tracking authorization dialog was shown
                    // and we are authorized
                    print("Authorized")
                case .denied:
                    // Tracking authorization dialog was
                    // shown and permission is denied
                    print("Denied")
                case .notDetermined:
                    // Tracking authorization dialog has not been shown
                    print("Not Determined")
                case .restricted:
                    print("Restricted")
                @unknown default:
                    print("Unknown")
                }
            })
        } else {
            //you got permission to track, iOS 14 is not yet installed
        }
    }
    override func applicationDidBecomeActive(_ application: UIApplication) {
        print("applicationDidBecomeActive");
        requestDataPermission()

//      application.applicationIconBadgeNumber = 0;
    }
        override func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken : Data){
            print("X__APNS: \(String(describing: deviceToken))")
            print("DeviceToken => ",deviceToken)
            Messaging.messaging().apnsToken = deviceToken;
        }
        
        override func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
            print("X_ERR",error);
        }
        
    override func application(_ application: UIApplication, didReceiveRemoteNotification
       userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("APN recieved")
        // print(userInfo)
        debugPrint("Received: \(userInfo)")

        let state = application.applicationState
        completionHandler(.newData)

        switch state {
            
        case .inactive:
            print("Inactive")
//            application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1

        case .background:
            print("Background")
            // update badge count here
            application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1
            
            
        case .active:
            print("Active")

        }
    }
    }


    
extension AppDelegate : MessagingDelegate{
 func messaging(_messagin : Messaging, didRecieveRegistrationToken fcmToken : String){
     self.firebaseToken = fcmToken;
     print("fcm token =>",self.firebaseToken)
     print("X__FCM: \(String(describing: fcmToken))")
 }
 func messaging(_messagin : Messaging, didRecieve remoteMessage : Any){
     print("REMOTE__MSG: \(remoteMessage)")
 }
 
   
   
}


