// lib/Utility/connectivityService.dart
import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';

class MyConnectivity {
  MyConnectivity._();

  static final MyConnectivity _instance = MyConnectivity._();
  static MyConnectivity get instance => _instance;

  final Connectivity _connectivity = Connectivity();
  final _controller = StreamController<bool>.broadcast();

  Stream<bool> get stream => _controller.stream;
  bool _lastState = true;   // assume online at start

  void initialise() async {
    // initial check
    final result = await _connectivity.checkConnectivity();
    await _checkInternet(result);

    // listen for changes
    _connectivity.onConnectivityChanged.listen(_checkInternet);
  }

  Future<void> _checkInternet(List<ConnectivityResult> results) async {
    final type = results.isEmpty ? ConnectivityResult.none : results.first;
    if (type == ConnectivityResult.none) {
      _emit(false);
      return;
    }

    bool online = false;
    final client = HttpClient()
      ..connectionTimeout = const Duration(seconds: 6);

    try {
      final request = await client.getUrl(Uri.parse('https://www.google.com'));
      request.followRedirects = false;
      final response = await request.close();
      online = response.statusCode >= 200 && response.statusCode < 400;
    } on SocketException {
      online = false;
    } on TimeoutException {
      online = false;
    } catch (_) {
      online = false;
    } finally {
      client.close();
    }

    _emit(online);
  }

  void _emit(bool online) {
    if (_lastState != online) {
      _lastState = online;
      _controller.sink.add(online);
    }
  }

  void dispose() => _controller.close();
}