package vs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;

@ServerEndpoint("/chat")
public class ChatServer {
	private static List<Session> clients = new ArrayList<>();

	@OnOpen
	public void open(Session session) {
		synchronized (clients) {
			clients.add(session);
		}
		try {
			session.getBasicRemote().sendText("Verbindung wurde hergestellt.");
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}
	}

	@OnClose
	public void close(Session session) {
		synchronized (clients) {
			clients.remove(session);
		}
	}

	@OnMessage
	public void message(Session session, String message) throws IOException {
		synchronized (clients) {
			for (Session client : clients) {
				if (client.isOpen() && !client.getId().equals(session.getId()))
					client.getBasicRemote().sendText("client#" + session.getId() + ": " + message);
			}
		}
	}

	@OnError
	public synchronized void error(Session session, Throwable ex) throws IOException {
		synchronized (clients) {
			for (Session client : clients) {
				if (client.isOpen())
					client.getBasicRemote().sendText("client#" + session.getId() + ": " + ex.getMessage());
			}
		}
	}
}
