package projet;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint("/ws/tchat")
public class Tchat {
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(String message, Session senderSession) throws IOException {
        String[] parts = message.split(" : ", 2);
        if (parts.length == 2) {
            String login = parts[0].trim();
            String contenu = parts[1].trim();
            
            Message.ajouterMessage(login, contenu);
            
	        synchronized (sessions) {
	            for (Session session : sessions) {
	                if (session.isOpen()) {
	                	session.getBasicRemote().sendText(message);
	                }
	            }
	        }
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
    	sessions.remove(session);
    	throwable.printStackTrace();
    }
}
