//
//  AppDelegate.swift
//  wallpaper_project


import UIKit
import IQKeyboardManagerSwift
import AppLovinSDK
import FirebaseCore
import FirebaseAnalytics
import Alamofire
import FBSDKCoreKit
import MTGSDK
import AnyThinkSDK

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var overlayWindow: UIWindow?
    var logTextView: UITextView?
    
    
    var wasInBackground = false
    static var shared: AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
    
    var isFirstLaunchq: Bool = true
    var window: UIWindow?
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    
    let hasLaunchedBeforeKey = "hasLaunchedBefore"
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        FirebaseApp.configure()
        ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
        
        IQKeyboardManager.shared.enable = true
        let splashViewController = WA_limitsVCViewController()
        // 设置启动视图控制器为应用程序的根视图控制器
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = splashViewController
        self.window?.makeKeyAndVisible()
        
        setdispatch()
        
        initializationTopOn.toponeSDK()
     
        let userDefaults = UserDefaults.standard
        if userDefaults.bool(forKey: hasLaunchedBeforeKey){
            let tt = UserDefaults.standard
           print("-------\(tt.bool(forKey: "iswindows"))")
        }else{
            //第一次启动
            UserDefaults.standard.set(true, forKey: hasLaunchedBeforeKey)
            UserDefaults.standard.set(false, forKey: "iswindows")
        }
 
        Analytics.logEvent("goin_app", parameters: nil)
        
        // 强制设置浅色模式
        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 applicationDidEnterBackground(_ application: UIApplication) {
 
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {

    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {

    }
    

    
    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.")
        }
    }
    func showOverlayWindow() {
        // 创建一个新的窗口，设置其大小和位置
        let overlaySize = CGSize(width: 200, height: 300)
        let overlayOrigin = CGPoint(x: UIScreen.main.bounds.width - overlaySize.width,
                                    y: (UIScreen.main.bounds.height - overlaySize.height) - 200)
        overlayWindow = UIWindow(frame: CGRect(origin: overlayOrigin, size: overlaySize))
        
        // 设置窗口级别高于状态栏
        overlayWindow?.windowLevel = UIWindow.Level.statusBar + 1
        overlayWindow!.isUserInteractionEnabled = true
        
        // 创建一个自定义视图
        let overlayView = UIView(frame: overlayWindow!.bounds)
        overlayView.isUserInteractionEnabled = true
        overlayView.backgroundColor = UIColor.red.withAlphaComponent(0.5) // 半透明红色背景
        overlayWindow?.addSubview(overlayView)
        
        //        let btn = UIButton(frame: overlayWindow!.bounds)
        //        btn.addTarget(self, action: #selector(showOverlayView), for: .touchUpInside)
        
        // 创建并配置 TextView
        logTextView = UITextView(frame: overlayView.bounds.insetBy(dx: 10, dy: 10))
        logTextView?.backgroundColor = UIColor.clear
        logTextView?.textColor = UIColor.white
        logTextView?.isEditable = false
        logTextView?.isScrollEnabled = true
        overlayView.addSubview(logTextView!)
        //        overlayView.addSubview(btn)
        // 设置根视图控制器
        //        overlayWindow?.rootViewController = UIViewController()
        overlayWindow?.isHidden = false
    }
    
    func removeOverlayWindow() {
        overlayWindow?.isHidden = true  // 隐藏窗口
        overlayWindow = nil  // 释放窗口
    }
    
    
    func addLogMessage(_ message: String) {
        if logTextView != nil {
            let currentText = logTextView?.text ?? ""
            let updatedText = "\(message)\n\n\(currentText)"
            logTextView?.text = updatedText
            
            // 滚动到文本的开头
            let range = NSMakeRange(0, 0)
            logTextView?.scrollRangeToVisible(range)
        } else {
            print("Log TextView is not initialized.")
        }
    }
    
}


