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

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:flutter/material.dart';
import 'package:trans_lark/util/log_print.dart';

class AppTrackingAuthorizationManager {
  AppTrackingAuthorizationManager._();

  static final AppTrackingAuthorizationManager _instance = AppTrackingAuthorizationManager._();

  factory AppTrackingAuthorizationManager() {
    return _instance;
  }

  Timer? _timer;

  /// 请求跟踪授权
  Future<void> requestTrackingAuthorization() 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();
          LogPrint.d('跟踪授权状态: $status');
        } else {
          _startTimer();
        }
      } else {
        _stopTimer();
      }
    }
  }

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

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