//
//  AV_RootPlayerVC.swift
//  anniversary_Project
//
//  Created by 忆海16 on 2024/7/21.
//

import UIKit
import AppLovinSDK
import Alamofire
import FirebaseRemoteConfig

class AV_RootPlayerVC: AV_RootVC {
    
    var retryAttempt = 0.0
    var interstitialAd1: MAInterstitialAd!
    var interstitialAd2: MAInterstitialAd!
    var interstitialAd3: MAInterstitialAd!
    var adCheckTimer: Timer?
    var adCheckStartTime: Date?
    var adLoadTime: Int = 0
    

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        steIDFA()
        self.createInterstitialAd()
    }
    
    
    @IBAction func backHome(_ sender: Any) {
        let appDelegate = UIApplication.shared.delegate
        appDelegate?.window??.rootViewController = AV_NAVVC(rootViewController: AV_WaterHomeVC())
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.navigationController?.navigationBar.isHidden = true

    }
    
    func steIDFA(){
        requestTrackingAuthorization { idfa in
                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.")
                }
        }
    }
    
    
//    bee9f7039e56cc7a
    @IBAction func one(_ sender: Any) {
        
        let vc = AV_AddPlayerVC()
        vc.interstitialAd = self.interstitialAd1
//        vc.createInterstitialAd()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
//    8fccdfa964b52e26
    @IBAction func two(_ sender: Any) {
        
        let vc = AV_MinePlayerVC()
//        vc.createInterstitialAd()
        vc.interstitialAd = self.interstitialAd2
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    
//    7baed02646413e44
    @IBAction func three(_ sender: Any) {
        
        let vc = AV_WaterKeyBordPlayerVC()
        vc.interstitialAd = self.interstitialAd3
//        vc.createInterstitialAd()
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
 
    
//    func setLoaded1(){
//        let parameters:[String : Any] = [
//            "appid": "com.countdown.day.daycount",
//            "idfa":StartManager.shared.idfaid ?? "",
//               "ads": [
//                   [
//                       "id": StartManager.shared.idOneAD,
//                       "btn_position": [
//                        "x": StartManager.shared.idOnex,
//                           "y": StartManager.shared.idOney
//                       ],
//                       "ecpm": StartManager.shared.idOne ?? ""
//                   ]
//               ]
//        ]
//        NetworkManager.shared.postRequest(url: StartManager.shared.loadurl, parameters: parameters, headers: StartManager.shared.headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//                if let status = data["status"] as? String, status == "Success" {
//                         if let needLoad = data["needload"] as? Int {
//                             if needLoad > 0 {
//                                 print("Need to load \(needLoad) more ads.")
//                                 // 执行加载更多广告的逻辑
//                             } else {
//                                 print("No need to load more ads.")
//                                 // 不需要加载更多广告的逻辑
//                             }
//                         }
//                     }
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//    
//    func setLoaded2(){
//        let parameters:[String : Any] = [
//            "appid": "com.countdown.day.daycount",
//            "idfa":StartManager.shared.idfaid ?? "",
//               "ads": [
//                   [
//                       "id": StartManager.shared.idTwoAD,
//                       "btn_position": [
//                        "x": StartManager.shared.idTwox,
//                           "y": StartManager.shared.idTwoy
//                       ],
//                       "ecpm": StartManager.shared.idTwo ?? ""
//                   ]
//               ]
//        ]
//        NetworkManager.shared.postRequest(url: StartManager.shared.loadurl, parameters: parameters, headers: StartManager.shared.headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//                if let status = data["status"] as? String, status == "Success" {
//                         if let needLoad = data["needload"] as? Int {
//                             if needLoad > 0 {
//                                 print("Need to load \(needLoad) more ads.")
//                                 // 执行加载更多广告的逻辑
//                             } else {
//                                 print("No need to load more ads.")
//                                 // 不需要加载更多广告的逻辑
//                             }
//                         }
//                     }
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
//
//    func setLoaded3(){
//        let parameters:[String : Any] = [
//            "appid": "com.countdown.day.daycount",
//            "idfa":StartManager.shared.idfaid ?? "",
//               "ads": [
//                   [
//                       "id": StartManager.shared.idThreeAD,
//                       "btn_position": [
//                        "x": StartManager.shared.idThreex,
//                           "y": StartManager.shared.idThreey
//                       ],
//                       "ecpm": StartManager.shared.idThree ?? ""
//                   ]
//               ]
//        ]
//        NetworkManager.shared.postRequest(url: StartManager.shared.loadurl, parameters: parameters, headers:StartManager.shared.headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//                if let status = data["status"] as? String, status == "Success" {
//                         if let needLoad = data["needload"] as? Int {
//                             if needLoad > 0 {
//                                 print("Need to load \(needLoad) more ads.")
//                                 // 执行加载更多广告的逻辑
//                             } else {
//                                 print("No need to load more ads.")
//                                 // 不需要加载更多广告的逻辑
//                             }
//                         }
//                     }
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//        
//    }
    
    
    func setLoaded1() {
        let idfa = StartManager.shared.idfaid
        let adId = StartManager.shared.idOneAD
        let btnPositionX = StartManager.shared.idOnex
        let btnPositionY = StartManager.shared.idOney
        let ecpm = StartManager.shared.idOneprice

        AdLoader.shared.loadAds( idfa: idfa, adId: adId, btnPositionX: btnPositionX, btnPositionY: btnPositionY, ecpm: ecpm) { result in
              switch result {
              case .success(let needLoad):
                  if needLoad > 0 {
                      print("Need to load \(needLoad) more ads.")
                      // 执行加载更多广告的逻辑
                  } else {
                      print("No need to load more ads.")
                      // 不需要加载更多广告的逻辑
                  }
              case .failure(let error):
                  print("Error:--- \(error)")
              }
          }
    }
    
    func setLoaded2() {
        let idfa = StartManager.shared.idfaid
        let adId = StartManager.shared.idTwoAD
        let btnPositionX = StartManager.shared.idTwox
        let btnPositionY = StartManager.shared.idTwoy
        let ecpm = StartManager.shared.idTwoprice

        AdLoader.shared.loadAds( idfa: idfa, adId: adId, btnPositionX: btnPositionX, btnPositionY: btnPositionY, ecpm: ecpm) { result in
              switch result {
              case .success(let needLoad):
                  if needLoad > 0 {
                      print("Need to load \(needLoad) more ads.")
                      // 执行加载更多广告的逻辑
                  } else {
                      print("No need to load more ads.")
                      // 不需要加载更多广告的逻辑
                  }
              case .failure(let error):
                  print("Error:--- \(error)")
              }
          }
    }
    
    func setLoaded3() {
        let idfa = StartManager.shared.idfaid
        let adId = StartManager.shared.idThreeAD
        let btnPositionX = StartManager.shared.idThreex
        let btnPositionY = StartManager.shared.idThreey
        let ecpm = StartManager.shared.idThreeprice

        AdLoader.shared.loadAds( idfa: idfa, adId: adId, btnPositionX: btnPositionX, btnPositionY: btnPositionY, ecpm: ecpm) { result in
              switch result {
              case .success(let needLoad):
                  if needLoad > 0 {
                      print("Need to load \(needLoad) more ads.")
                      // 执行加载更多广告的逻辑
                  } else {
                      print("No need to load more ads.")
                      // 不需要加载更多广告的逻辑
                  }
              case .failure(let error):
                  print("Error:--- \(error)")
              }
          }
    }
    
    
//    func setclosed(adid:String){
//        let parameters:[String : Any] = [
//            "appid": "com.countdown.day.daycount",
//            "idfa":StartManager.shared.idfaid ?? "",
//            "id":adid,
//            
//        ]
//        NetworkManager.shared.postRequest(url: StartManager.shared.closedUrl, parameters: parameters, headers: StartManager.shared.headers) { result in
//            switch result {
//            case .success(let data):
//                print("Response:--- \(data)")
//            case .failure(let error):
//                print("Error:--- \(error)")
//            }
//        }
//    }

}

extension AV_RootPlayerVC: MAAdDelegate
{
    func createInterstitialAd()
    {
        
        if StartManager.shared.IDADType == 1{
            interstitialAd1 = MAInterstitialAd(adUnitIdentifier: "bee9f7039e56cc7a")
            interstitialAd1.delegate = self
            
            // Load the first ad
            interstitialAd1.load()
        }else if StartManager.shared.IDADType == 2{
            interstitialAd2 = MAInterstitialAd(adUnitIdentifier: "8fccdfa964b52e26")
            interstitialAd2.delegate = self
            
            // Load the first ad
            interstitialAd2.load()
        }else if StartManager.shared.IDADType == 3{
            
            interstitialAd3 = MAInterstitialAd(adUnitIdentifier: "7baed02646413e44")
            interstitialAd3.delegate = self
            
            // Load the first ad
            interstitialAd3.load()
        }

        
        
    }
    
    // MARK: MAAdDelegate Protocol
    
    func didLoad(_ ad: MAAd)
    {
        // Interstitial ad is ready to be shown. 'interstitialAd.isReady' will now return 'true'
        // 插页式广告已准备好显示。'interstitialAd.isReady' 现在将返回 'true'

        // 重置重试尝试
        // Reset retry attempt
        retryAttempt = 0
        StartManager.shared.succeed = true
        //        StartManager.shared.loadTime = self.adLoadTime
        StartManager.shared.adPlatform = "MAX"
        StartManager.shared.countryCode = ALSdk.shared().configuration.countryCode
        StartManager.shared.adId = "bee9f7039e56cc7a"
        StartManager.shared.platformResponseTime = ad.requestLatency
        StartManager.shared.ecpm = Float(ad.revenue)
        StartManager.shared.dsp = ad.dspName
        StartManager.shared.network = ad.networkName
//        StartManager.shared.idOne = Float(ad.revenue)
        print("----idOne\(Float(ad.revenue))")
//        setPostload()
        
        if StartManager.shared.IDADType == 1{
            StartManager.shared.idOneprice = Float(ad.revenue)
            self.setLoaded1()
            StartManager.shared.IDADType = 2
            createInterstitialAd()
        }else if StartManager.shared.IDADType == 2{
            StartManager.shared.idTwoprice = Float(ad.revenue)
            self.setLoaded2()
            StartManager.shared.IDADType = 3
            createInterstitialAd()
        }else if StartManager.shared.IDADType == 3{
            StartManager.shared.idThreeprice = Float(ad.revenue)
            self.setLoaded3()
        }
    }
    
    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)
        // 插页广告加载失败
        // 我们建议以指数级更高的延迟重试，最大延迟为 64 秒
        
        retryAttempt += 1
        let delaySec = pow(2.0, min(6.0, retryAttempt))
        
        DispatchQueue.main.asyncAfter(deadline: .now() + delaySec) {
            self.interstitialAd1.load()
        }
    }
    
    func didDisplay(_ ad: MAAd)
    {
        // Pause your app's background audio
        // 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
        // 恢复应用的背景音频
        // 插页式广告已隐藏。预加载下一个广告
//        interstitialAd1.load()
//        self.navigationController?.popViewController(animated: true)
//        setclosed(adid: ad.adUnitIdentifier)
        AdLoader.shared.closeAd(idfa: StartManager.shared.idfaid, adId: ad.adUnitIdentifier) { result in
            switch result {
                  case .success(let data):
                      print("Response:--- \(data)")
                  case .failure(let error):
                      print("Error:--- \(error)")
                  }
        }
        navigationController?.popViewController(animated: true)
        
    }
    
    func didFail(toDisplay ad: MAAd, withError error: MAError)
    {
        // Interstitial ad failed to display. We recommend loading the next ad
        // 插页广告显示失败。建议加载下一个广告
//        interstitialAd.load()
    }
}
