// Author: fengshengxiong
// Date: 2024/6/26
// Description: 网络连接服务

import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart';
import 'package:tone_snap/ads/app_open_ad_manager.dart';
import 'package:tone_snap/ads/interstitial_ad_manager.dart';
import 'package:tone_snap/firebase/firebase_remote_config_manager.dart';
import 'package:tone_snap/modules/launch/launch_controller.dart';
import 'package:tone_snap/utils/log_util.dart';

class NetworkConnectivityService extends GetxService {
  StreamSubscription<List<ConnectivityResult>>? subscription;
  /// 是否执行过以下任务，任务只执行一次
  var isExecutedTask = false;

  @override
  void onInit() {
    super.onInit();
    subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      LogUtil.d('当前网络连接类型：$result');
      if (result.contains(ConnectivityResult.wifi) || result.contains(ConnectivityResult.mobile)) {
        if (!isExecutedTask) {
          isExecutedTask = true;

          FirebaseRemoteConfigManager.getAll();

          if (Get.isRegistered<LaunchController>()) {
            LaunchController.to.getIsoCode();
          }

          InterstitialAdManager().loadAd();
          AppOpenAdManager().loadAd();
        }
      }
    });
  }

  @override
  void onClose() {
    subscription?.cancel();
    super.onClose();
  }
}