//
//  AppDelegate.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/19.i
//

import ADManager
import AppTrackingTransparency
import GoogleMobileAds
import StoreKit
import TSVideoKit
import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        window?.makeKeyAndVisible()
        goToLoadVC()
        initBaseDatas()
        downloadNotifaction()
        return true
    }

    func goToTab() {
        window?.rootViewController = TSTabBarController()
    }

    func goToLoadVC() {
        _ = TSImageDataCenter.shared
        window?.rootViewController = TSLaunchVC()
    }

    func initBaseDatas() {
        var config = TSConfiguration.default
        config.configurePath = "http://p.100yearslater.com/live/config"
        TSVideoOperator.shared.loadWithConfiguration(config: config, needJs: true)

        if let videoId = UserDefaults.standard.string(forKey: "lastedVideoId"),
           !videoId.isEmpty,
           let lastVideo = TSVideoOperator.shared.dataManager.fetchVideo(videoId: videoId) {
            TSVideoOperator.shared.playerViewModel.currentVideo = lastVideo
            TSVideoOperator.shared.playerViewModel.currentVideos = TSVideoOperator.shared.dataManager.fetchCachedVideos()
            PlayerManager.shared.miniBar.updateVideoInfo(video: lastVideo, state: .pause)
        }

        if let loopMode = UserDefaults.standard.string(forKey: "lastedPlayMode") {
            let mMode = LoopMode(rawValue: loopMode) ?? .cyclic
            TSVideoOperator.shared.playerViewModel.loopMode = mMode
        }
    }

    @objc func recordData() {
        if UserDefaults.standard.value(forKey: "CachedTag") == nil {
            UserDefaults.standard.setValue("1", forKey: "CachedTag")
            SKStoreReviewController.requestReview()
        }
    }

    func downloadNotifaction() {
        NotificationCenter.default.addObserver(self, selector: #selector(recordData), name: kGroupDownloadFinishNotifactionName, object: nil)
    }

    static func requestAdTrack() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
                // 这里可以处理用户的选择
                switch status {
                case .authorized:
                    print("授权成功，可以开始跟踪")
                case .denied:
                    print("用户拒绝了授权")
                case .restricted:
                    print("该设备的用户无法授权")
                case .notDetermined:
                    print("用户尚未做出选择")
                @unknown default:
                    print("未知状态")
                }
            })
        }
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        AppDelegate.requestAdTrack()
    }

    func applicationWillTerminate(_ application: UIApplication) {
        UserDefaults.standard.setValue(PlayerManager.shared.currentVideo?.videoId ?? "", forKey: "lastedVideoId")
        UserDefaults.standard.setValue(PlayerManager.shared.currentLoopMode.rawValue, forKey: "lastedPlayMode")
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // 热启动显示开屏广告
        if let topVC = UIApplication.defaultViewController?.topVc {
            if PurchaseManager.default.isVip {
                return
            }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                ADManager.shared.showLaunchAdWhenActive(scene: ADScene.launch, from: topVC)
            }
        }
    }
}

extension AppDelegate {
}
