
import UIKit
import OneSignalFramework
import GoogleMobileAds
import Combine

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, OSNotificationLifecycleListener, OSPushSubscriptionObserver, OSNotificationClickListener {
    
    
    var window: UIWindow?
    var orientationLock = UIInterfaceOrientationMask.all
    public var userID:String?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        MobileAds.shared.start(completionHandler: nil)
        if Settings.PUSH_ENABLED {
            // Initialize with your OneSignal App ID
            OneSignal.initialize("75755d0b-56eb-4c5f-b713-22367ac3dad2", withLaunchOptions: launchOptions)
            
            OneSignal.Notifications.addForegroundLifecycleListener(self)

            // Manually prompt for push notifications
            OneSignal.Notifications.requestPermission({ accepted in
                print("User accepted notifications: \(accepted)")
                if accepted {
                    UserDefaults.standard.set(true, forKey: "isAllowed")
                    Settings.PUSH_ENABLED = true
                } else {
                    UserDefaults.standard.set(false, forKey: "isAllowed")
                    Settings.PUSH_ENABLED = false
                }
              }, fallbackToSettings: true)
        }

        
        return true
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
        let isallowed = UIApplication.shared.isRegisteredForRemoteNotifications
               print(isallowed)
        //print("opened again")
    }
    
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        let suffix = url.absoluteString.components(separatedBy: "//")[1]
        var passingURL = ""
        if suffix != "" {
            passingURL = composeURL(url: url.absoluteString)
            print("new url is: \(Settings.URL)")
        }
    
        DispatchQueue.main.async {
            let vc = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "homeController") as? ContainerController
            if passingURL != "" {vc?.passingURL = passingURL}
            self.window?.rootViewController = vc
        }
        return true
    }
    
    func composeURL(url: String)-> String {
        let httpsPart = Settings.URL.components(separatedBy: "//")[0]
        let domain = Settings.URL.components(separatedBy: "//")[1]
        var mainDomain = ""
        if domain.contains("/"){
            mainDomain = domain.components(separatedBy: "/")[0]
        } else {
            mainDomain = domain
        }
        let suffix = url.components(separatedBy: "//")[1]
        
        return httpsPart + "//" + mainDomain + "/" + suffix
    }
    
    func onClick(event: OSNotificationClickEvent) {
        let notification = event.notification

                // Access additional data from the notification payload
                if let additionalData = notification.additionalData,
                   let url = additionalData["url"] as? String {
                    UserDefaults.standard.set(url, forKey: "launchURL")
                    
                    DispatchQueue.main.async {
                        let vc = UIStoryboard(name: "Main", bundle: nil)
                            .instantiateViewController(withIdentifier: "homeController")
                        self.window?.rootViewController = vc
                    }
                }
    }
    
    func onWillDisplay(event: OSNotificationWillDisplayEvent) {
        
    }
    

    func onPushSubscriptionDidChange(state: OSPushSubscriptionChangedState) {
        // Respond to state change
        if let subscriptionId = state.current.id {
            print("Subscription ID: \(subscriptionId)")
        } else {
            print("state is: \(state)")
        }
    }
    
}


