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

import UIKit
import IQKeyboardManagerSwift
import AppLovinSDK
import FirebaseCore
import FirebaseAnalytics

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    var interstitialAd: MAInterstitialAd!
    var retryAttempt = 0.0
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        FirebaseApp.configure()
        
        IQKeyboardManager.shared.enable = true
        let splashViewController = WA_limitsVCViewController()
        // 设置启动视图控制器为应用程序的根视图控制器
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = splashViewController
        self.window?.makeKeyAndVisible()
        
        let isFirstLaunch = UserDefaults.standard.bool(forKey: "isFirstLaunch")
        
        if !isFirstLaunch {
            // 第一次运行应用程序时执行的代码
            AccountManager.createDefaultAccountIfNeeded()
            
            // 设置 isFirstLaunch 标志为 true
            UserDefaults.standard.set(true, forKey: "isFirstLaunch")
        }
        
        let initConfig = ALSdkInitializationConfiguration(sdkKey: "O9SUDhhvnysqkmTqrvetcbJ1wp1OHnxXF9xdpu2TmR4Ppq3w35mn3d2iy2g4OHvGWPl0EJ6D7H5FpGK5izye1A") { builder in
            builder.mediationProvider = ALMediationProviderMAX
        }

        // Initialize the SDK with the configuration
        ALSdk.shared().initialize(with: initConfig) { sdkConfig in
          // Start loading ads
        }
        
        self.createInterstitialAd()
        if interstitialAd.isReady {
            interstitialAd.show()
        }else{
            print("-------广告没准备好")
        }
        
        if UserDefaults.standard.object(forKey: "issave") != nil {
//            return UserDefaults.standard.bool(forKey: "issave")
            issave(false)
        } else {
            // 默认返回未登录状态
            issave(false)
        }
        if UserDefaults.standard.object(forKey: "issure") != nil {
//            return UserDefaults.standard.bool(forKey: "issave")
            issure(false)
        } else {
            // 默认返回未登录状态
            issure(false)
        }
        
        Analytics.logEvent("goin_app", parameters: nil)
        
        
        return true
    }
    
    
    func applicationDidFinishLaunching(_ application: UIApplication) {
        let initConfig = ALSdkInitializationConfiguration(sdkKey: "O9SUDhhvnysqkmTqrvetcbJ1wp1OHnxXF9xdpu2TmR4Ppq3w35mn3d2iy2g4OHvGWPl0EJ6D7H5FpGK5izye1A") { builder in

          builder.mediationProvider = ALMediationProviderMAX

          // Perform any additional configuration/setting changes
        }
    }
    
}

extension AppDelegate: MAAdDelegate
{
    func createInterstitialAd()
    {
        interstitialAd = MAInterstitialAd(adUnitIdentifier: "789b377f3ac4010e")
        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
    }
    
    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()
            
        WA_TabbarCommon.TabBarController()

    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError)
    {
        // Interstitial ad failed to display. We recommend loading the next ad
        interstitialAd.load()
    }
}
