import 'package:fis_jsonrpc/rpc.dart';

final _host = _ProxyHost();

/// JSON-RPC client proxy
JsonRpcProxy get rpc => _host.getProxy();

class _ProxyHost {
  JsonRpcProxy? _proxy;

  /// JSON-RPC client
  JsonRpcProxy getProxy() {
    if (_proxy == null) {
      _init();
    }
    return _proxy!;
  }

  /// 初始化代理
  void _init() {
    _buildProxy();
    // _listenServerHostChange();
  }

  /// 构建代理实例
  void _buildProxy() {
    final originServerHost = _proxy?.currentHostAddress;
    JsonRpcProxy jsonRpcProxy = JsonRpcProxy();
    _proxy = jsonRpcProxy;
    if (originServerHost != null && originServerHost.isNotEmpty) {
      _setRpcHost(_proxy!, originServerHost);
    }
    // _proxy!.addInterceptor(_DefaultInterceptor());
    // _proxy!.addInterceptor(JsonRpcExInterceptor());
  }

  // /// 监听服务地址变更
  // void _listenServerHostChange() {
  //   bus.on(bus.Keys.SERVER_ADDRESS_CHANGED, (arg) {
  //     logger.i('EventBus - [${bus.Keys.SERVER_ADDRESS_CHANGED}]: $arg');
  //     _setRpcHost(rpc, arg);
  //     rpc.clearCache();
  //   });
  // }

  static void _setRpcHost(JsonRpcProxy rpc, url) {
    final uri = Uri.parse(url);
    rpc.setServerHost("${uri.host}:${uri.port}", uri.scheme == "https");
  }
}

extension JsonRpcProxyExt on JsonRpcProxy {
  //
}
