//
//  LUXTopOnConfigure.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/8/5.
//

import Foundation
import AppTrackingTransparency
import AdSupport
import Firebase
import FirebaseRemoteConfig

class LUXTopOnConfigure {
    static let shared = LUXTopOnConfigure()
    var attTimer: Timer?
    private init() {
        // 初始化代码
    }
         
    @objc func checkATT() {
         if #available(iOS 14, *) {
             ATTrackingManager.requestTrackingAuthorization { status in
                 // 获取到权限后，依然使用老方法获取idfa
                 if status == .notDetermined {
                     if self.attTimer == nil {
                         self.attTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.checkATT), userInfo: nil, repeats: true)
                         
                         ATTrackingManager.requestTrackingAuthorization { status in
                             if status != .notDetermined {
                                 print("用户已做出选择")
                                 self.invalidATTTimer()
                             } else {
                                 print("用户未做出选择,可能是弹框未弹出...")
                             }
                         }
                     }
                 } else {
                     self.invalidATTTimer()
                 }
             }
         }
     }
     
     @objc func invalidATTTimer() {
         attTimer?.invalidate()
         attTimer = nil
     }
    
    func configureADByFirebase(with window: UIWindow) {
           FirebaseApp.configure()
           
        if LUXToponManager.shared.isADSSMode() {
            self.configureAD(window: window)
           } else {
               // 读取 firebase 数据
               let rc = RemoteConfig.remoteConfig()
               let rcs = RemoteConfigSettings()
               rcs.minimumFetchInterval = 0
               rc.configSettings = rcs
               
               rc.fetchAndActivate { status, error in
                   DispatchQueue.main.async {
                       if status == .successFetchedFromRemote {
                           let localVer = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
                           if let value = rc.configValue(forKey: "isopen").jsonValue as? [String: Any],
                              let isadopen = value["isadopen"] as? Bool,
                              let version = value["version"] as? String {
                               if !isadopen || (version == localVer) {
                                   self.configureRootVC(window: window)
                               } else {
                                   self.configureAD(window: window)
                               }
                           }
                       } else {
                           DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
                               self.configureADByFirebase(with: window)
                           }
                       }
                   }
               }
           }
       }
    
    func configureAD(window:UIWindow){
        LUXToponManager.shared.configureadWithTopOn()
        
        
        LUXToponManager.shared.addAD(withInterstitialId: "n66acb8888353f") { vc in
//            let onevc = OneVc()
//            onevc.adIndex = 1
//            vc.navigationController?.pushViewController(onevc, animated: true)
        }
        LUXToponManager.shared.addAD(withInterstitialId: "n66acb8894e8df") { vc in
            let onevc = OneVc()
            onevc.adIndex = 1
            vc.navigationController?.pushViewController(onevc, animated: true)
        }
        LUXToponManager.shared.addAD(withInterstitialId: "n66acb888b9441") { vc in
            let onevc = OneVc()
            onevc.adIndex = 2
            vc.navigationController?.pushViewController(onevc, animated: true)
        }
        LUXToponManager.shared.addAD(withInterstitialId: "n66acb8891f516") { vc in
            let onevc = OneVc()
            onevc.adIndex = 3
            vc.navigationController?.pushViewController(onevc, animated: true)
        }
        
    }
    
    
    func configureRootVC(window: UIWindow?) {
        let hasLaunchedBeforeKey = "hasLaunchedBefore"
        
        window?.frame = UIScreen.main.bounds
        
        let userDefaults = UserDefaults.standard

            let vc = WA_NewHomeVC()
            window?.rootViewController = WA_RootNAV(rootViewController: vc)

    }
    
    
}
