import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';

import '../utils/logs_utils.dart';

class ConnectivityHelper {
  final Connectivity _connectivity = Connectivity();

  late StreamSubscription<List<ConnectivityResult>> _subscription;

  static bool isNetworkConnected = false;

  checkNetworkConnectivity() async {
    initConnectivity();
    _subscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  }

  disposeConnectivity() {
    _subscription.cancel();
  }

  Future<void> initConnectivity() async {
    List<ConnectivityResult> result;
    try {
      result = await _connectivity.checkConnectivity();
    } catch (e) {
      result = [ConnectivityResult.none];
    }
    _updateConnectionStatus(result);
  }

  void _updateConnectionStatus(List<ConnectivityResult> result) {
    dp("Connectivity result is", result);
    result.forEach(
          (e) {
        if (e == ConnectivityResult.none || e == ConnectivityResult.bluetooth || e == ConnectivityResult.other) {
          isNetworkConnected = false;
        } else {
          isNetworkConnected = true;
        }
      },
    );
  }

}
