//
//  TSAppUpdateManager.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/6/18.
//


public extension Notification.Name {
    static let kAppUpdateNotification = Notification.Name("kAppUpdateNotification")
}

class TSAppUpdateManager {

    static var newVerison:String = ""
    static var isNeedUpdate:Bool = false
    
    static var tabbarDotShow:Int = 0 //0,无需显示,1 需要显示,2 显示后隐藏
    
    static var isDisplayedUpdateAlert:Bool = false
    
    static func checkAppConfig() {
        _ = TSNetworkShared.get(urlType: .config) { data, _ in
            if let result = kNetWorkResultSuccess(data: data) {
                newVerison = result.safeString(forKey: "version")
                dePrint("checkAppConfig 刷新版本号refreshView = \(newVerison),appShortVersion=\(appShortVersion())")
                if compareAppVersions(newVersion1: newVerison, oldVersion: appShortVersion()) {
                    isNeedUpdate = true
                }else{
                    isNeedUpdate = false
                }
                
                if isNeedUpdate,tabbarDotShow != 2 {
                    tabbarDotShow = 1
                }
            }
            kMainAsync{
                NotificationCenter.default.post(name: .kAppUpdateNotification, object: nil)
            }
            
        }
    }

    public static func compareAppVersions(newVersion1: String, oldVersion: String) -> Bool {
        let components1 = newVersion1.components(separatedBy: ".")
        let components2 = oldVersion.components(separatedBy: ".")
        
        let maxLength = max(components1.count, components2.count)
        
        for i in 0..<maxLength {
            let num1 = i < components1.count ? Int(components1[i]) ?? 0 : 0
            let num2 = i < components2.count ? Int(components2[i]) ?? 0 : 0
        
            if num1 > num2 {
                return true
            }
        }
        
        return false
    }
}
