// Author: fengshengxiong
// Date: 2024/6/26
// Description: 应用程序跟踪透明度管理器

import 'dart:async';
import 'dart:io';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flutter_translate/common/utils/log_utils.dart';

class AppTrackingTransparencyManager {
  AppTrackingTransparencyManager._();

  static final AppTrackingTransparencyManager _instance = AppTrackingTransparencyManager._();

  factory AppTrackingTransparencyManager() {
    return _instance;
  }

  Timer? _timer;

  /// 请求跟踪授权
  Future<void> requestATT() async {
    if (Platform.isIOS) {
      final TrackingStatus status = await AppTrackingTransparency.trackingAuthorizationStatus;
      if (status == TrackingStatus.notDetermined) {
        if (_timer != null && _timer!.isActive) {
          final TrackingStatus status = await AppTrackingTransparency.requestTrackingAuthorization();
          Log.d('跟踪授权状态: $status');
        } else {
          _startTimer();
        }
      } else {
        _stopTimer();
      }
    }
  }

  /// 开始定时器
  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 3), (Timer t) {
      requestATT();
    });
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
