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

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get/get.dart';

typedef NetworkStatusCallback = void Function(bool isConnected);

class NetworkUtils {
  static final NetworkUtils _instance = NetworkUtils._internal();

  factory NetworkUtils() => _instance;

  NetworkUtils._internal();

  final Connectivity _connectivity = Connectivity();
  StreamSubscription<List<ConnectivityResult>>? _subscription;

  /// RxBool 响应式网络状态
  final RxBool _isConnected = false.obs;

  /// 初始化网络监听
  void initialize({NetworkStatusCallback? onStatusChange}) async {
    // 先检查一次当前网络
    _isConnected.value = await checkNetworkAvailable();
    onStatusChange?.call(_isConnected.value);

    // 监听网络变化
    _subscription = _connectivity.onConnectivityChanged.listen((result) async {
      bool newStatus = await checkNetworkAvailable();
      if (newStatus != _isConnected.value) {
        _isConnected.value = newStatus;
        onStatusChange?.call(_isConnected.value);
      }
    });
  }

  /// 检查网络是否可用
  Future<bool> checkNetworkAvailable() async {
    final connectivityResult = await _connectivity.checkConnectivity();
    if (connectivityResult.first == ConnectivityResult.none) return false;

    try {
      final result = await InternetAddress.lookup('wuzhongjie.com.cn');
      return result.isNotEmpty && result[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      return false;
    }
  }

  /// 当前网络状态（响应式访问）
  RxBool get isConnected => _isConnected;

  /// 取消监听
  void dispose() {
    _subscription?.cancel();
  }
}
