//
//  AppDelegate.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/11.
//

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

@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()
        
        let mtgsdk = MTGSDK()
        mtgsdk.setAppID("302071", apiKey: "8e642b70b909c249688ccbc7d7d7a164")
        
//        let initConfig = ALSdkInitializationConfiguration(sdkKey: "O9SUDhhvnysqkmTqrvetcbJ1wp1OHnxXF9xdpu2TmR4Ppq3w35mn3d2iy2g4OHvGWPl0EJ6D7H5FpGK5izye1A") { builder in
//            builder.mediationProvider = ALMediationProviderMAX
//        }
//        
//        ALSdk.shared().initialize(with: initConfig) { sdkConfig in
//            // Start loading ads
//            splashViewController.createInterstitialAd()
//            
////            let vc = WA_DetailsVC()
////            vc.createInterstitialAd()
////            
////            let rakvc = WA_RankingVC()
////            rakvc.createInterstitialAd()
//            
//        }
        
        
        Analytics.logEvent("goin_app", parameters: nil)
        
//        let userDefaults = UserDefaults.standard
        
      
        
        // 强制设置浅色模式
        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) {
        // 应用进入后台时调用
//        wasInBackground = true
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        //         应用即将从后台进入前台时调用
//        if wasInBackground {
//            // 这里执行你希望在应用从后台进入前台时执行的代码
//            self.createInterstitialAd()
//            print("Application will enter foreground")
//        }
    }
    
    func applicationDidBecomeActive(_ application: UIApplication) {
//        if wasInBackground {
//            adCheckStartTime = Date()
//            adCheckTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(checkAdStatus), userInfo: nil, repeats: true)
//        }
//        // 应用已经变为活跃状态时调用
//        print("Application did become active")
//        wasInBackground = false
    }
    
//    @objc func checkAdStatus(){
//        let elapsedTime = Date().timeIntervalSince(adCheckStartTime!)
//        if interstitialAd.isReady {
//            interstitialAd.show()
//            Analytics.logEvent("Backstage_load_success", parameters: nil)
//            self.setPostSHOW()
//            adCheckTimer?.invalidate()
//        } else if elapsedTime >= 2 {
//            adCheckTimer?.invalidate()
//            //            WA_TabbarCommon.TabBarController()
//            Analytics.logEvent("Backstage_load_fail", parameters: nil)
//        } else {
//            print("广告未准备好，继续检查...")
//        }
//    }
    
    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.")
        }
    }
    
}


//extension AppDelegate: MAAdDelegate
//{
//    func createInterstitialAd()
//    {
//        interstitialAd = MAInterstitialAd(adUnitIdentifier: "8e1bc1f22c8d6c9d")
//        interstitialAd.delegate = self
//        
//        // Load the first ad
//        interstitialAd.load()
//    }
//    
//    // MARK: MAAdDelegate Protocol
//    
//    func didLoad(_ ad: MAAd)
//    {
//        // Interstitial ad is ready to be shown. 'interstitialAd.isReady' will now return 'true'
//        
//        // Reset retry attempt
//        retryAttempt = 0
//        StartManager.shared.succeed = true
//        StartManager.shared.loadTime = 0
//        StartManager.shared.adPlatform = "MAX"
//        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
//        StartManager.shared.adId = "8e1bc1f22c8d6c9d"
//        StartManager.shared.platformResponseTime = ad.requestLatency
//        StartManager.shared.ecpm = Float(ad.revenue)
//        StartManager.shared.dsp = ad.dspName
//        StartManager.shared.network = ad.networkName
//        let logMessage = """
//            deviceId: \(StartManager.shared.devicID ?? "")
//            localIp: \(StartManager.shared.localIP ?? "")
//            "deviceId": \(StartManager.shared.devicID ?? ""),
//            "localIp": \(StartManager.shared.localIP ?? ""),
//            "remoteIp": \(StartManager.shared.publicIP ?? ""),
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": \(StartManager.shared.idfaid ?? ""),
//            "dataId": "",
//            "shelfNumber": "后台进入前台",
//            "succeed": \(StartManager.shared.succeed),
//            "loadTime": \(StartManager.shared.loadTime ?? 0),
//            "adPlatform": \(StartManager.shared.adPlatform ?? ""),
//            "countryCode": \(StartManager.shared.countryCode ?? ""),
//            "adId": \(StartManager.shared.adId ?? ""),
//            "platformResponseTime": \(StartManager.shared.platformResponseTime ?? 0.0),
//            "getIpResponseTime": \(StartManager.shared.getIpResponseTime ?? 0.0),
//            "ecpm": \(StartManager.shared.ecpm ?? 0.0),
//            "dsp": \(StartManager.shared.dsp ?? ""),
//            "network": \(StartManager.shared.network ?? "")
//            """
//        
//        AppDelegate.shared.addLogMessage(logMessage)
//        
//        self.setPostload()
//    }
//    
//    func didFailToLoadAd(forAdUnitIdentifier adUnitIdentifier: String, withError error: MAError)
//    {
//        // Interstitial ad failed to load
//        // We recommend retrying with exponentially higher delays up to a maximum delay (in this case 64 seconds)
//        
//        retryAttempt += 1
//        let delaySec = pow(2.0, min(6.0, retryAttempt))
//        
//        DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
//            self.interstitialAd.load()
//        }
//    }
//    
//    func didDisplay(_ ad: MAAd)
//    {
//        // Pause your app's background audio
//    }
//    
//    func didClick(_ ad: MAAd) {
//        
//    }
//    
//    func didHide(_ ad: MAAd)
//    {
//        // Resume your app's background audio
//        // Interstitial ad is hidden. Pre-load the next ad
//        interstitialAd.load()
//        
//        
//    }
//    
//    func didFail(toDisplay ad: MAAd, withError error: MAError)
//    {
//        // Interstitial ad failed to display. We recommend loading the next ad
//        interstitialAd.load()
//    }
    
//    
//    func setPostload(){
//        let url = "http://111.9.47.226:38080/top_selection/save_ad_load_log"
//        let parameters:[String : Any] = [
//            "deviceId": StartManager.shared.devicID ?? "",
//            "localIp": StartManager.shared.localIP ?? "",
//            "remoteIp": StartManager.shared.publicIP ?? "",
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": StartManager.shared.idfaid ?? "",
//            "dataId": "",
//            "shelfNumber":"后台进入前台",
//            "succeed": StartManager.shared.succeed,
//            "loadTime":StartManager.shared.loadTime ?? "",
//            "adPlatform": StartManager.shared.adPlatform ?? "",
//            "countryCode": StartManager.shared.countryCode ?? "",
//            "adId": StartManager.shared.adId ?? "",
//            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
//            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
//            "ecpm": StartManager.shared.ecpm ?? "",
//            "dsp": StartManager.shared.dsp ?? "",
//            "network": StartManager.shared.network ?? "",
//            "showStatus": 0,
//            "washParam": true,
//        ]
//        
//        
//        let headers: HTTPHeaders = [
//            "Content-Type": "application/json"
//        ]
//        
//        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//    
//    
//    func setPostSHOW(){
//        let url = "http://111.9.47.226:38080/top_selection/save_ad_show_log"
//        let parameters:[String : Any] = [
//            "deviceId": StartManager.shared.devicID ?? "",
//            "localIp": StartManager.shared.localIP ?? "",
//            "remoteIp": StartManager.shared.publicIP ?? "",
//            "linkId": "",
//            "packageName": "com.wallpapaer.hd.live.app",
//            "gaid": StartManager.shared.idfaid ?? "",
//            "dataId": "",
//            "shelfNumber":"后台进入前台",
//            "succeed": StartManager.shared.succeed,
//            "loadTime":StartManager.shared.loadTime ?? "",
//            "adPlatform": StartManager.shared.adPlatform ?? "",
//            "countryCode": StartManager.shared.countryCode ?? "",
//            "adId": StartManager.shared.adId ?? "",
//            "platformResponseTime": StartManager.shared.platformResponseTime ?? "",
//            "getIpResponseTime": StartManager.shared.getIpResponseTime ?? "",
//            "ecpm": StartManager.shared.ecpm ?? "",
//            "dsp": StartManager.shared.dsp ?? "",
//            "network": StartManager.shared.network ?? "",
//        ]
//        
//        let headers: HTTPHeaders = [
//            "Content-Type": "application/json"
//        ]
//        
//        NetworkManager.shared.postRequest(url: url, parameters: parameters, headers: headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//    
//}
