import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:vnote_device_plugin/events/event_type.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';

/// 网络连接检测器 - 全局实例
final netChecker = _init();

NetworkConnectivityChecker _init() {
  final instance = NetworkConnectivityChecker._();

  instance.onlineChangedEvent.addListener((sender, e) {
    if (e) {
      PromptBox.toast("网络已连接");
    } else {
      PromptBox.error("网络已断开");
    }
  });

  return instance;
}

/// 网络连接检查器
class NetworkConnectivityChecker {
  NetworkConnectivityChecker._();

  final Connectivity _api = Connectivity();
  StreamSubscription<ConnectivityResult>? _subscription;
  ConnectivityResult _status = ConnectivityResult.none;

  /// 在线状态变更事件
  final FEventHandler<bool> onlineChangedEvent = FEventHandler<bool>();

  /// 连接状态
  ConnectivityResult get status => _status;

  /// 是否在线
  bool get isOnline => status != ConnectivityResult.none;

  void run() {
    if (_subscription != null) {
      return;
    }
    _subscription = _api.onConnectivityChanged.listen((event) {
      print("ConnectivityResult: ${event.name}");
      final originIsOnline = isOnline;
      _status = event;
      if (originIsOnline != isOnline) {
        onlineChangedEvent.emit(this, isOnline);
      }
    });
  }

  void stop() {
    _subscription?.cancel();
    _subscription = null;
  }
}
