package com.armundia.core.websocket;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.websocket.Session;

import com.armundia.core.websocket.pojo.SessionContainer;


@ApplicationScoped
public class WebSocketApplication {
	private static final Logger logger = Logger.getLogger(WebSocketApplication.class.getName());
	
	private	Set<SessionContainer> sessions;
	
	
	@PostConstruct
	public void postConstruct() {
		sessions = Collections.synchronizedSet(new LinkedHashSet<>());
	}
	
	public void addSession(Session session) {
		SessionContainer sc = new SessionContainer(session);
		sessions.add(sc);
		
		logger.info("Added new session: " + session.getId());
	}
	
	public Set<SessionContainer> getSessions(){
		return this.sessions;
	}
	
	public SessionContainer getSession(Session session) {
		SessionContainer sessionContainer = sessions
				.stream()
				.filter(sc -> sc.session.equals(session))
				.findFirst()
				.get();

		return sessionContainer;
	}
	
	public void removeSession(Session session) {
		SessionContainer sessionContainer = sessions
				.stream()
				.filter(sc -> sc.session.equals(session))
				.findFirst()
				.get();

		sessions.remove(sessionContainer);
	}
}
