//
//  AppDelegate.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/4/11.
//

import UIKit
import IQKeyboardManagerSwift    
import Photos
import Alamofire
import SVProgressHUD
import AppLovinSDK
import FirebaseCore
import FirebaseAnalytics

import FBSDKCoreKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
    
    var window: UIWindow?
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        //        window = UIWindow()
        //        window?.frame = UIScreen.main.bounds
        IQKeyboardManager.shared.enable = true
        setNetwork()
        LuxADConfigure.shareInstance().checkATT()
        LuxADConfigure.shareInstance().configureADByFirebase(with: self.window!)
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        //        setdispatch()
       
        
        if (!LuxADManager.shareInstance().isADSSMode()){
            Analytics.logEvent("launch", parameters: nil)
        }
//        LuxADManager shareInstance].isADSSMode
        
        self.window?.makeKeyAndVisible()
        
        // 强制设置浅色模式
        if #available(iOS 13.0, *) {
            window?.overrideUserInterfaceStyle = .light
            
        }
        
        return true
    }
    func application(_ app: UIApplication,open url: URL,options:[UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )
    }
    
    
    // 当应用将要进入前台时调用（从后台到前台的过渡）
    func applicationWillEnterForeground(_ application: UIApplication) {
        
    }
    
    // 当应用已经进入前台并变为活跃状态时调用
    func applicationDidBecomeActive(_ application: UIApplication) {
        
        LuxADManager.shareInstance().showOpenAD()
        
    }
    
    
    
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
    
    func setNetwork(){
        // 创建一个URL对象
        if let url = URL(string: "https://www.google.com") {
            // 创建一个URLSession对象
            let session = URLSession.shared
            
            // 创建一个网络请求任务
            let task = session.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("网络请求出错：\(error)")

                }
            }
            
            // 开始网络请求任务
            task.resume()
        } else {
            print("URL无效")
        }
    }
    
}

func setdispatch(){
    // 使用信号量控制并发任务
    let dispatchGroup = DispatchGroup()
    
    // 请求跟踪授权并处理 IDFA
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        requestTrackingAuthorization { idfa in
            DispatchQueue.main.async {
                if let idfa = idfa {
                    print("IDFA: \(idfa)")
                    StartManager.shared.idfaid = idfa
                    print("Stored IDFA: \(StartManager.shared.idfaid ?? "N/A")")
                } else {
                    print("IDFA is not available or tracking authorization denied.")
                }
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取本地 IP 地址
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        if let localIP = getLocalIPAddress() {
            DispatchQueue.main.async {
                print("Local IP Address: \(localIP)")
                StartManager.shared.localIP = localIP
                dispatchGroup.leave()
            }
        } else {
            DispatchQueue.main.async {
                print("Local IP Address not available")
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取远程 IP 地址
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        getPublicIPAddress { publicIP in
            DispatchQueue.main.async {
                if let publicIP = publicIP {
                    print("Public IP Address: \(publicIP)")
                    StartManager.shared.publicIP = publicIP
                    print("Stored Public IP Address: \(StartManager.shared.publicIP ?? "N/A")")
                } else {
                    print("Public IP Address not available")
                }
                dispatchGroup.leave()
            }
        }
    }
    
    // 获取设备 ID
    dispatchGroup.enter()
    DispatchQueue.global(qos: .background).async {
        let deviceID = UIDevice.current.identifierForVendor?.uuidString
        DispatchQueue.main.async {
            StartManager.shared.devicID = deviceID
            print("Device ID: \(StartManager.shared.devicID ?? "N/A")")
            dispatchGroup.leave()
        }
    }
    
    // 所有任务完成后的操作
    dispatchGroup.notify(queue: .main) {
        print("All tasks are completed.")
    }
    
}



