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 Att {
  Att._();

  static final Att _instance = Att._();

  factory Att() {
    return _instance;
  }

  Timer? _timer;

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

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

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