/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.ocelotds.web;

import org.ocelotds.core.SessionManager;
import org.ocelotds.messaging.MessageEvent;
import org.ocelotds.messaging.MessageToClient;
import org.ocelotds.messaging.MessageType;
import java.util.ArrayList;
import java.util.Collection;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.websocket.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Singleton that send push messages
 *
 * @author hhfrancois
 */
public class TopicsMessagesBroadcaster {

	private final static Logger logger = LoggerFactory.getLogger(TopicsMessagesBroadcaster.class);

	@Inject
	private SessionManager sessionManager;

	/**
	 * Send message to topic
	 *
	 * @param msg
	 */
	public void sendMessageToTopic(@Observes @MessageEvent MessageToClient msg) {
		msg.setType(MessageType.MESSAGE);
		logger.debug("Sending message to topic {}...", msg);
		Collection<Session> sessions = sessionManager.getSessionsForTopic(msg.getId());
		if (!sessions.isEmpty()) {
			Collection<Session> closed = new ArrayList<>();
			for (Session session : sessions) {
				if (session.isOpen()) {
					session.getAsyncRemote().sendObject(msg);
				} else {
					closed.add(session);
				}
			}
			if(logger.isDebugEnabled()){
				logger.debug("Send message to '{}' topic {} client(s) : {}", new Object[]{msg.getId(), sessions.size()-closed.size(), msg});
			}
			if(!closed.isEmpty()) {
				logger.debug("Session closed to remove '{}'", closed.size());
				sessionManager.removeSessionsToTopic(sessions);
			}
		} else {
			logger.debug("No client for topic '{}'", msg.getId());
		}
	}
}

@@ -1227,16 +1227,36 @@
 %0D%0A%09%09if (
+sessions != null && 
 !session
@@ -1294,17 +1294,25 @@
 ession%3E 
-c
+sessionsC
 losed = 
@@ -1366,24 +1366,50 @@
 essions) %7B%0D%0A
+%09%09%09%09if(session!=null) %7B%0D%0A%09
 %09%09%09%09if (sess
@@ -1421,24 +1421,25 @@
 sOpen()) %7B%0D%0A
+%09
 %09%09%09%09%09session
@@ -1478,16 +1478,17 @@
 );%0D%0A%09%09%09%09
+%09
 %7D else %7B
@@ -1494,17 +1494,26 @@
 %7B%0D%0A%09%09%09%09%09
-c
+%09sessionsC
 losed.ad
@@ -1521,24 +1521,32 @@
 (session);%0D%0A
+%09%09%09%09%09%7D%0D%0A
 %09%09%09%09%7D%0D%0A%09%09%09%7D%0D
@@ -1551,16 +1551,17 @@
 %7D%0D%0A%09%09%09if
+ 
 (logger.
@@ -1577,16 +1577,17 @@
 abled())
+ 
 %7B%0D%0A%09%09%09%09l
@@ -1691,10 +1691,20 @@
 ze()
--c
+ - sessionsC
 lose
@@ -1736,11 +1736,20 @@
 %09%09if
+ 
 (!
-c
+sessionsC
 lose
@@ -1814,17 +1814,25 @@
  '%7B%7D'%22, 
-c
+sessionsC
 losed.si
@@ -1888,16 +1888,22 @@
 sessions
+Closed
 );%0D%0A%09%09%09%7D

fix bug remove sessions closed bad variable