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

import Alamofire
import UIKit
import AppTrackingTransparency

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

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

    private var isStop: Bool = false

    var showingAdViewController: Bool {
        return presentedViewController != nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupLaunchScreenView()
        kPurchaseBusiness.launchPrchase()

        addNotifiy()
        if AppDelegate.isFirstInstallApp() {//首次安装需要等待网络权限弹窗
            startTimer()
        }else{
            startTimer()
        }
    }


    func addNotifiy() {
        let networkManager = NetworkReachabilityManager.default
        networkManager?.startListening { status in
            switch status {
            case .reachable:
                kPurchaseBusiness.launchPrchase()
                networkManager?.stopListening()
            default:
                break
            }
        }
    }

    func enterApp() {
        dismissHandler?()
        DispatchQueue.main.async {
//            let keyWindow = WindowHelper.getCurrentWindow()
//            if (keyWindow?.rootViewController is CustomTabBarController) == false {
//                let vc = CustomTabBarController()
//                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() {
        let launchView = UIImageView(frame: UIScreen.main.bounds)
        launchView.image = UIImage(named: "launch2")
        launchView.contentMode = .scaleAspectFill
        view.addSubview(launchView)
    }
}
