import 'dart:async';
import 'dart:math';

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

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

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

  bool isConnecting = true;

  instance.onlineChangedEvent.addListener((sender, e) {
    if (e) {
      if (!isConnecting) {
        // TODO: 暂时不提示
        // PromptBox.toast("网络已连接");
      }
    } else {
      // TODO: 暂时不提示
      // PromptBox.error("网络已断开");
    }
    isConnecting = e;
  });

  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) {
      logger.i(
          "NetworkConnectivityChecker - Current net connection type: ${event.name}.");
      _update(event);
      logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
    });
  }

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

  /// 手动检查
  Future<bool> check() async {
    logger.i("NetworkConnectivityChecker - Check start.");
    final result = await _api.checkConnectivity();
    logger.i("NetworkConnectivityChecker - Check result:${result.name}.");
    _update(result);
    logger.i("NetworkConnectivityChecker - IsOnline: $isOnline.");
    return isOnline;
  }

  void _update(ConnectivityResult result) {
    _status = result;
    onlineChangedEvent.emit(this, isOnline);
  }
}
