//
//  TSLaunchVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

import Alamofire
import UIKit
import GoogleMobileAds

class TSLaunchVC: UIViewController {
    var dismissHandler: (() -> Void)?

    // 定时器
    private var timer: DispatchSourceTimer?
    // 闪屏页剩余显示时长
    #if DEBUG
        private var remindTimeInterval: TimeInterval = 5.0
    #else
        private var remindTimeInterval: TimeInterval = 5.0
    #endif

    private var isStop: Bool = false

    var showingAdViewController: Bool {
        return presentedViewController != nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupLaunchScreenView()
        startTimer()
        addNotifiy()
    }

    func addNotifiy() {
        TSNetworkShard.startListenNetStatus { status, manager in
            switch status {
            case .reachable:
                PurchaseManager.default.requestProducts()
                AppDelegate.requestAdTrack()
                manager?.stopListening()
                self.initAdMob()
            default:
                AppDelegate.requestAdTrack()
                PurchaseManager.default.requestProducts()
                self.initAdMob()
                break
            }
        }
    }

    func initAdMob() {
        GADMobileAds.sharedInstance().start { status in
            print("启动状态 == status === \(status.adapterStatusesByClassName)")
        }
    }

    func enterApp() {
        DispatchQueue.main.async {
            let keyWindow = WindowHelper.getCurrentWindow()
            if (keyWindow?.rootViewController is TSTabBarController) == false {
                let vc = TSTabBarController()
                keyWindow?.rootViewController = vc
                keyWindow?.makeKeyAndVisible()
            } else if let _ = self.presentingViewController {
                self.dismiss(animated: false)
            }
            self.dismissHandler?()
        }
    }

    private func startTimer() {
        if timer == nil {
            timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
            timer?.schedule(deadline: .now(), repeating: .milliseconds(200))
            timer?.setEventHandler(handler: { [weak self] in
                // App活跃时，计时有效；如网络授权弹窗唤起时，计时失效
                DispatchQueue.main.async {
                    guard let self = self,
                          UIApplication.shared.applicationState == .active,
                          !self.showingAdViewController else {
                        return
                    }
                    self.remindTimeInterval -= 0.2
                    print("倒计时：\(self.remindTimeInterval)")
                    if self.remindTimeInterval <= 0 {
                        self.timer?.cancel()
                        self.enterApp()
                    }
                }

            })
            timer?.resume()
        }
    }

    private func setupLaunchScreenView() {
        // 获取 LaunchScreen.storyboard 的视图控制器
        let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
        guard let launchVC = storyboard.instantiateInitialViewController() else {
            debugPrint("无法加载 LaunchScreen 的初始视图控制器")
            return
        }

        // 获取 LaunchScreen 的视图
        guard let launchView = launchVC.view else {
            debugPrint("无法获取 LaunchScreen 的视图")
            return
        }

        // 设置 launchView 的 frame 为当前视图的 bounds
        launchView.frame = UIScreen.main.bounds

        // 将 launchView 添加到 TSLaunchVC 的视图中
        view.addSubview(launchView)
    }
}

