import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';

abstract class ConnectivityService {
  void subscribeToConnectivityChange({
    required Function() onInternetDisConnected,
    required Function() onInternetConnected,
  });

  Future<String> getCurrentScreenIP();
}

class ConnectivityServiceImp implements ConnectivityService {
  Connectivity connectivityInstance;

  ConnectivityServiceImp({required this.connectivityInstance});

  @override
  subscribeToConnectivityChange({
    required Function() onInternetDisConnected,
    required Function() onInternetConnected,
  }) {
    connectivityInstance.onConnectivityChanged.listen((List<ConnectivityResult> event) async {
      switch (event.first) {
        case ConnectivityResult.wifi:
        case ConnectivityResult.ethernet:
          onInternetConnected();
          break;
        case ConnectivityResult.none:
          onInternetDisConnected();
          break;
        case ConnectivityResult.mobile:
        case ConnectivityResult.bluetooth:
        case ConnectivityResult.vpn:
        case ConnectivityResult.other:
          break;
      }
    });
  }

  @override
  Future<String> getCurrentScreenIP() async {
    const eth = "eth0";
    const wlan = "wlan0";
    String currentDeviceIp = "";
    final ips = await NetworkInterface.list(type: InternetAddressType.IPv4);
    for (var interface in ips) {
      if (interface.name == eth) {
        for (var address in interface.addresses) {
          currentDeviceIp = address.address;
        }
      }
      if (interface.name == wlan) {
        for (var address in interface.addresses) {
          currentDeviceIp = address.address;
        }
      }
    }
    return currentDeviceIp;
  }
}
