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

class InternetController extends GetxController {

  var isOnline = true.obs;
  bool lastStatus = true;

  final Connectivity _connectivity = Connectivity();

  @override
  void onInit() {
    super.onInit();
    checkConnection();

    _connectivity.onConnectivityChanged.listen((results) {
      updateConnection(results);
    });
  }

  Future<void> checkConnection() async {
    final results = await _connectivity.checkConnectivity();
    updateConnection(results);
  }

  void updateConnection(List<ConnectivityResult> results) {

    bool currentStatus = !results.contains(ConnectivityResult.none);

    if (currentStatus != lastStatus) {

      if (!currentStatus) {

        isOnline.value = false;

        Get.snackbar(
          "Tidak ada internet",
          "Periksa koneksi internet Anda",
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red,
          colorText: Colors.white,
          duration: const Duration(seconds: 3),
        );

      } else {

        isOnline.value = true;

        Get.snackbar(
          "Koneksi kembali",
          "Internet sudah tersambung",
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green,
          colorText: Colors.white,
          duration: const Duration(seconds: 3),
        );

      }

      lastStatus = currentStatus;
    }
  }
}