//
//  WA_limitsVCViewController.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/3/18.
//

import UIKit
import SVProgressHUD
import Photos
import Alamofire
import AppLovinSDK
import FirebaseAnalytics

class WA_limitsVCViewController: WA_RootVC {
    @IBOutlet weak var retryBtn: UIButton!
    let activityView = UIActivityIndicatorView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // 创建和加载插页广告
        
        
//        activityView.center = CGPoint(x: self.view.center.x, y: self.view.center.y - kSafeArea_Top - 44)
//        // 停止后，隐藏菊花
//        activityView.hidesWhenStopped = true
//        activityView.color = .black
//        activityView.style = UIActivityIndicatorView.Style.whiteLarge
//        self.view.addSubview(activityView)
//        self.activityView.startAnimating()
        requestPhotoLibraryPermission()
        
        checkNetworkPermission()
        // 创建和加载插页广告
        //           createInterstitialAd()
        
        DispatchQueue.global().asyncAfter(deadline: .now() + 8) {
            self.setNetwork()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.retryBtn.isHidden = true
       
        
        
    }
    func requestPhotoLibraryPermission() {
        // 检查相册权限状态
        let status = PHPhotoLibrary.authorizationStatus()
        
        // 根据权限状态进行处理
        switch status {
        case .authorized:
            // 用户已授权访问相册
            print("相册权限已授权")
        case .denied, .restricted:
            // 用户已拒绝访问相册或权限受限
            print("相册权限已拒绝或受限，请在设置中开启权限")
        case .notDetermined:
            // 用户尚未作出选择，请求相册权限
            PHPhotoLibrary.requestAuthorization { [weak self] (newStatus) in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        // 用户授权访问相册
                        print("用户已授权访问相册")
                    } else {
                        // 用户未授权访问相册
                        print("用户未授权访问相册")
                    }
                }
            }
        @unknown default:
            // 处理未知权限状态
            print("未知的相册权限状态")
        }
    }
    
    
    
    func setNetwork(){
        // 创建一个URL对象
        if let url = URL(string: "https://www.baidu.com/") {
            // 创建一个URLSession对象
            let session = URLSession.shared
            
            // 创建一个网络请求任务
            let task = session.dataTask(with: url) { (data, response, error) in
                if let error = error {
                    print("网络请求出错：\(error)")
                    DispatchQueue.main.asyncAfter(deadline: .now()){
//                        self.activityView.stopAnimating()
                        SVProgressHUD.showInfo(withStatus: "Network connection failed, please try again")
                        self.retryBtn.isHidden = false
                        DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                            SVProgressHUD.dismiss()
                            
                        }
                    }
                } else if let data = data {
                    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
//                        appDelegate.showInterstitialAd()
                        // 如果插页广告已经准备好显示，立即显示广告
                        if appDelegate.interstitialAd.isReady {
                            appDelegate.interstitialAd.show()

                            Analytics.logEvent("open_load_success", parameters: nil)
                            
                        }else{
                            print("-------广告没准备好")
                            Analytics.logEvent("open_load_fail", parameters: nil)
                            self.retryBtn.isHidden = false
                        }
                    }
                    
                }
            }
            
            // 开始网络请求任务
            task.resume()
        } else {
            print("URL无效")
        }
    }
    
    // 检查网络权限状态
    func checkNetworkPermission() {
        let status = NetworkReachabilityManager.default?.status
        switch status {
        case .notReachable:
            SVProgressHUD.showInfo(withStatus: "No internet connection")
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                SVProgressHUD.dismiss()
                
            }
            print("没有网络连接")
        case .unknown:
            print("网络状态未知")
            SVProgressHUD.showInfo(withStatus: "Network status unknown")
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                SVProgressHUD.dismiss()
                
            }
        case .reachable(.ethernetOrWiFi):
            print("使用WiFi连接")
        case .reachable(.cellular):
            print("使用蜂窝网络连接")
        case .none:
            SVProgressHUD.showInfo(withStatus: "Network permission is not authorized")
            DispatchQueue.global().asyncAfter(deadline: .now() + 2.0) {
                SVProgressHUD.dismiss()
                
                
                print("网络权限未授权")
            }
        }
    }
    // 请求网络权限
    func requestNetworkPermission() {
        NetworkReachabilityManager.default?.startListening(onUpdatePerforming: { status in
            print("网络状态更新: \(status)")
        })
    }
    
    // 停止监听网络状态
    func stopListeningNetwork() {
        NetworkReachabilityManager.default?.stopListening()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    
    @IBAction func btnRetry(_ sender: Any) {

        setNetwork()
    }
    

    
}
