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

import 'package:shelf/shelf.dart' as shelf;
import 'package:shelf/shelf_io.dart' as shelf_io;
import 'package:shelf_web_socket/shelf_web_socket.dart';
import 'package:web_socket_channel/io.dart'; // Import IOWebSocketChannel

void webSocketServer(SendPort sendPort) async {
  final clients = <IOWebSocketChannel>[]; // Use IOWebSocketChannel

  final handler = webSocketHandler((webSocket) {
    clients.add(webSocket);
    webSocket.stream.listen(
          (message) {
        print('Received: $message');
        for (var client in clients) {
          if (client != webSocket) {
            client.sink.add(message); // Broadcast the message to other clients
          }
        }
      },
      onDone: () {
        clients.remove(webSocket);
      },
    );
  });

  final server = await shelf_io.serve(
    shelf.Pipeline().addMiddleware(shelf.logRequests()).addHandler(handler),
    '0.0.0.0',
    8080,
  );

  print('WebSocket server running at ws://${server.address.host}:${server.port}');
  sendPort.send('Server running at ws://${server.address.host}:${server.port}');
}
