//
//  AppDelegate.swift
//  SodaLive
//
//  Created by klaus on 2023/08/09.
//

import UIKit

import FirebaseCore
import FirebaseMessaging

class AppDelegate: UIResponder, UIApplicationDelegate {
    
    private let gcmMessageIDKey = "gcm.message_id"
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        Messaging.messaging().delegate = self
        
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        
        application.registerForRemoteNotifications()
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        return true
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        Messaging.messaging().appDidReceiveMessage(userInfo)
        // Print message ID.
        if let messageID = userInfo[gcmMessageIDKey] {
            DEBUG_LOG("Message ID: \(messageID)")
        }
        
        // Print full message.
        DEBUG_LOG("userInfo: \(userInfo)")
        
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        UserDefaults.set(deviceToken, forKey: .devicePushToken)
        Messaging.messaging().apnsToken = deviceToken
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    }
}

extension AppDelegate: MessagingDelegate {
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        if let fcmToken = fcmToken {
            DEBUG_LOG("fcmToken: \(fcmToken)")
            UserDefaults.set(fcmToken, forKey: .pushToken)
        }
    }
}

extension AppDelegate : UNUserNotificationCenterDelegate {
    
    // Receive displayed notifications for iOS 10 devices.
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        let userInfo = notification.request.content.userInfo
        
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        
        // ...
        
        // Print full message.
        DEBUG_LOG("userInfo: \(userInfo)")
        
        // Change this to your preferred presentation option
        completionHandler([.banner, .badge, .sound])
    }
    
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        
        // With swizzling disabled you must let Messaging know about the message, for Analytics
        Messaging.messaging().appDidReceiveMessage(userInfo)
        
        let roomIdString = userInfo["room_id"] as? String
        let contentIdString = userInfo["content_id"] as? String
        let channelIdString = userInfo["channel_id"] as? String
        let messageIdString = userInfo["message_id"] as? String
        
        if let roomIdString = roomIdString, let roomId = Int(roomIdString), roomId > 0 {
            AppState.shared.pushRoomId = roomId
        }
        
        if let contentIdString = contentIdString, let audioContentId = Int(contentIdString), audioContentId > 0 {
            AppState.shared.pushAudioContentId = audioContentId
        }
        
        if let channelIdString = channelIdString, let channelId = Int(channelIdString), channelId > 0 {
            AppState.shared.pushChannelId = channelId
        }
        
        if let messageIdString = messageIdString, let messageId = Int(messageIdString), messageId > 0 {
            AppState.shared.pushMessageId = messageId
        }
        
        completionHandler()
    }
}