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

import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_translate/ads/interstitial_ad_manage.dart';
import 'package:flutter_translate/common/components/dialog/remind_dialog.dart';
import 'package:flutter_translate/common/hive/remote_config_box.dart';
import 'package:flutter_translate/common/utils/log_utils.dart';
import 'package:flutter_translate/firebase/firebase_remote_config_manager.dart';
import 'package:flutter_translate/pages/launch/launch_controller.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

class NetworkConnectivityService extends GetxService {
  StreamSubscription<List<ConnectivityResult>>? subscription;
  var isShowNetworkDialog = false;

  @override
  void onInit() {
    super.onInit();
    subscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) async {
      Log.d('当前网络连接类型：$result');
      if (result.contains(ConnectivityResult.none)) {
        _checkNetworkDialog();
        isShowNetworkDialog = true;
      } else {
        if (Get.isRegistered<LaunchController>()) {
          if (LaunchController.to.timer == null) {
            LaunchController.to.startTimer();
          }
        }
        Log.d('检查网络弹窗状态：${Get.isDialogOpen}');
        if (Get.isDialogOpen != null && Get.isDialogOpen! && isShowNetworkDialog) {
          Get.back();
          isShowNetworkDialog = false;
        }
        bool adSwitch = RemoteConfigBox().getAdSwitch();
        if (adSwitch) {
          InterstitialAdManager().loadAllAd();
        } else {
          await FirebaseRemoteConfigManager.getAll();
        }
      }
    });
  }

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

  void _checkNetworkDialog() {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: 'No network connection\nPlease check the current network',
        showCancelBtn: false,
        enableBack: false,
        confirmOnTap: () {
          openAppSettings();
        },
      ),
    );
  }
}