import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EchoServer {

    private int port = 1234;
    private boolean running = true;
    private ServerSocket serverSocket;
    private static EchoServer instance;
    private List<Connection> connections;
    private ExecutorService threadPool;

    private EchoServer(){
        try {
            // ServerSocket auf Port 1234 erstellen
            serverSocket = new ServerSocket(port);
            // Liste für Verbindungen initialisieren
            connections = new ArrayList<>();
            // ThreadPool für Verbindungen erstellen
            threadPool = Executors.newCachedThreadPool();

            System.out.println("Server läuft auf Port " + port);
        }
        catch (IOException e){
            System.out.println(e);
        }
    }

    public static EchoServer getInstance(){
        if (instance == null) {
            instance = new EchoServer();
        }
        return instance;
    }

    public void waitForConnections() {
        while (running) {
            try {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client verbunden: " + clientSocket.getInetAddress());

                // Neue Verbindung erstellen und zur Liste hinzufügen
                Connection connection = new Connection(clientSocket, this);
                connections.add(connection);

                // Verbindung in einem neuen Thread ausführen
                threadPool.submit(connection);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void broadcastMessage(String message, Connection origin) {
        for (Connection connection : connections) {
            if (connection != origin) {  // Nachricht nicht an Ursprung senden
                connection.sendMessage(message);
            }
        }
    }

    public static void main(String args[]) {
        EchoServer server = EchoServer.getInstance();
        server.waitForConnections();
    }
}
