//
//  idfaManager.swift
//  wallpaper_project
//
//  Created by 忆海16 on 2024/6/4.
//

import Foundation
import UIKit
import AdSupport
import AppTrackingTransparency



func requestTrackingAuthorization(completion: @escaping (String?) -> Void) {
    if #available(iOS 14, *) {
        var attemptsLeft = 3
        
        func requestAuth() {
            ATTrackingManager.requestTrackingAuthorization { status in
                switch status {
                case .authorized:
                    let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                    print("Authorized: IDFA = \(idfa)")
                    completion(idfa)
                case .denied, .restricted:
                    print("Denied or Restricted")
                    completion(nil)
                case .notDetermined:
                    print("Not Determined")
                    attemptsLeft -= 1
                    if attemptsLeft > 0 {
                        requestAuth() // 继续请求直到达到最大尝试次数
                    } else {
                        print("Reached maximum number of attempts")
                        completion(nil)
                    }
                @unknown default:
                    print("Unknown status")
                    completion(nil)
                }
            }
        }
        
        requestAuth() // 第一次请求
    } else {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            print("Tracking enabled: IDFA = \(idfa)")
            completion(idfa)
        } else {
            print("Tracking not enabled")
            completion(nil)
        }
    }
}



func requestIDFA(completion: @escaping (String?) -> Void) {
    if #available(iOS 14, *) {
        ATTrackingManager.requestTrackingAuthorization { status in
            switch status {
            case .authorized:
                let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
                completion(idfa)
            default:
                completion(nil)
            }
        }
    } else {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            completion(idfa)
        } else {
            completion(nil)
        }
    }
}
