//
//  IDFAManager.swift
//  sunoAi
//
//  Created by leon on 2024/4/9.
//

import Foundation
import AppTrackingTransparency
import AdSupport
import Flutter

class IDFAManager{
    
    static func getIDFA(call: FlutterMethodCall, result: @escaping FlutterResult) {
        
        if #available(iOS 14.0, *){//ios14以上系统 请求用户授权
            
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier
                    DebugPrint("IDFA 用户同意了授权: \(idfa.uuidString)")
                    initGravityEngineSDK(call: call, result: result, idfa: idfa.uuidString)
                case .denied:
                    DebugPrint("IDFA 用户拒绝了授权")
                    initGravityEngineSDK(call: call, result: result, idfa: "")
                case .restricted:
                    DebugPrint("IDFA 应用无法请求授权，可能由于限制")
                    initGravityEngineSDK(call: call, result: result, idfa: "")
                case .notDetermined:
                    DebugPrint("IDFA 用户尚未做出选择")
                    initGravityEngineSDK(call: call, result: result, idfa: "")
                @unknown default:
                    break
                }
            }
            
        }else{//ios14以下系统 请求用户授权
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                let idfa = ASIdentifierManager.shared().advertisingIdentifier
                DebugPrint("ios14以下系统 IDFA 用户同意了授权: \(idfa)")
                initGravityEngineSDK(call: call, result: result, idfa: idfa.uuidString)
            } else {
                DebugPrint("ios14以下系统 IDFA 用户拒绝了授权")
                initGravityEngineSDK(call: call, result: result, idfa: "")
            }
            
        }
        
    }
    
    //四种情况下都在这里初始化引力引擎sdk
    static func initGravityEngineSDK(call: FlutterMethodCall, result: @escaping FlutterResult, idfa:String){
        
        //引力引擎调用的时候需返回主线程加载 否则程序会崩溃
        DispatchQueue.main.async {
            if (GravityEnginePlugin.gravityEngineSDK == nil){
                GravityEnginePlugin.initialize(call: call, result: result, idfa: idfa)
            }
        }
        
    }
    
}

