import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'dart:async';

class Connectivityprovider extends ChangeNotifier {
  static final Connectivityprovider _instance = Connectivityprovider._();
  static Connectivityprovider get instance => _instance;

  final Connectivity _connectivity = Connectivity();
  bool _isOnline = false;
  Map<ConnectivityResult, bool> _source = {ConnectivityResult.none: false};

  Connectivityprovider._() {
    initialise();
  }

  bool get isOnline => _isOnline;
  Map<ConnectivityResult, bool> get source => _source;

  void initialise() async {
    List<ConnectivityResult> result = await _connectivity.checkConnectivity();
    _checkStatus(result.first);
    _connectivity.onConnectivityChanged.listen((result) {
      _checkStatus(result.first);
    });
  }

  void _checkStatus(ConnectivityResult result) async {
    bool isOnline = false;
    try {
      final lookupResult = await InternetAddress.lookup('example.com');
      isOnline =
          lookupResult.isNotEmpty && lookupResult[0].rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      isOnline = false;
    }
    _source = {result: isOnline};
    _isOnline = isOnline;
    notifyListeners(); // Notify all listeners of the change
  }

  void dispose() {
    // No StreamController to close, as we're using ChangeNotifier
  }
}
