import 'package:injectable/injectable.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_web_socket/shelf_web_socket.dart';

@LazySingleton()
class WebSocketService {
  final List<dynamic> _clients = [];

  Handler get handler => webSocketHandler((webSocket, _) {
    _clients.add(webSocket);
    print('Client connected, total: ${_clients.length}');

    webSocket.stream.listen(
      (message) {
        webSocket.sink.add('echo $message');
      },
      onDone: () {
        _clients.remove(webSocket);
        print('Client disconnected, total: ${_clients.length}');
      },
      onError: (error) {
        _clients.remove(webSocket);
        print('Client error: $error');
      },
      cancelOnError: true,
    );
  });
}
