// network_connectivity.dart

import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:tanami_app/core/routes/route_name.dart';
import 'package:tanami_app/core/routes/routes.dart';

/* CREATED BY - JAYESH JAIN 
   DATE - 24-05-2024 
 */

/// Class that handles network connectivity checks and updates.
class NetworkConnectivity {
  final Connectivity _connectivity = Connectivity();
  late StreamSubscription<List<ConnectivityResult>> _subscription;
  final Function(String) onStatusChange;

  NetworkConnectivity({required this.onStatusChange});

  /// Initializes the network connectivity checks and updates.
  void initialize() {
    _subscription = _connectivity.onConnectivityChanged
        .listen((List<ConnectivityResult> result) {
      String status = result.toString();
      onStatusChange(status);

      if (result[0] == ConnectivityResult.wifi ||
          result[0] == ConnectivityResult.mobile) {
        if (goRouter.canPop()) {
          goRouter.pop(true);
        }
      } else {
        goRouter.pushNamed(RouteName.noInternetScreen);
      }
    });

    checkInternet();
  }

  /// Checks the current network connectivity status.
  Future<void> checkInternet() async {
    final connectivityResult = await _connectivity.checkConnectivity();

    if (connectivityResult[0] != ConnectivityResult.none) {
      onStatusChange(connectivityResult.toString());
    } else {
      onStatusChange(connectivityResult.toString());
      goRouter.pushNamed(RouteName.noInternetScreen);
    }
  }

  /// Cancels the StreamSubscription that listens for connectivity changes.
  void dispose() {
    _subscription.cancel();
  }
}
