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

import SwiftUI
import AppTrackingTransparency

import FirebaseDynamicLinks

@main
struct SodaLiveApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    func handleIncomingDynamicLink(_ dynamicLink: DynamicLink) {
        guard let url = dynamicLink.url else {
            DEBUG_LOG("That's weired. My dynamic link object has no url")
            return
        }
        
        DEBUG_LOG("incoming link parameter is \(url.absoluteString)")
        
        let queryItems = URLComponents(url: url, resolvingAgainstBaseURL: true)?.queryItems
        let roomId = queryItems?.filter({$0.name == "room_id"}).first?.value
        let channelId = queryItems?.filter({$0.name == "channel_id"}).first?.value
        let messageId = queryItems?.filter({$0.name == "message_id"}).first?.value
        let audioContentId = queryItems?.filter({$0.name == "content_id"}).first?.value
        
        if let roomId = roomId {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                AppState.shared.pushRoomId = Int(roomId) ?? 0
            }
        }
        
        if let channelId = channelId {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                AppState.shared.pushChannelId = Int(channelId) ?? 0
            }
        }
        
        if let messageId = messageId {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                AppState.shared.pushMessageId = Int(messageId) ?? 0
            }
        }
        
        if let audioContentId = audioContentId {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                AppState.shared.pushAudioContentId = Int(audioContentId) ?? 0
            }
        }
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
                    CreatorCommunityMediaPlayerManager.shared.pauseContent()
                }
                .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                    UIApplication.shared.applicationIconBadgeNumber = 0
                    
                    ATTrackingManager.requestTrackingAuthorization { _ in }
                }
                .onOpenURL { url in
                    DEBUG_LOG("I have received a URL through a custom scheme! \(url.absoluteString)")
                    if let scheme = url.scheme {
                        if scheme == "kr.co.vividnext.sodalive" {
                            if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
                                self.handleIncomingDynamicLink(dynamicLink)
                            } else {
                                DEBUG_LOG("dynamic link fail")
                            }
                        } else {
                            DynamicLinks.dynamicLinks().handleUniversalLink(url) { dynamicLink, error in
                                guard error == nil else {
                                    DEBUG_LOG("Found an error! \(error!.localizedDescription)")
                                    DEBUG_LOG("dynamic link fail")
                                    return
                                }
                                
                                if let dynamicLink = dynamicLink {
                                    self.handleIncomingDynamicLink(dynamicLink)
                                } else {
                                    DEBUG_LOG("dynamic link fail")
                                }
                            }
                        }
                    }
                }
        }
    }
}
