package com.armundia.core.websocket;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.Stateful;
import javax.inject.Inject;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.armundia.app.test.TestManager;
import com.armundia.app.test.pojo.TestPojo;
import com.armundia.core.websocket.pojo.MessageDecoder;
import com.armundia.core.websocket.pojo.MessageEncoder;
import com.armundia.core.websocket.pojo.SessionContainer;
import com.armundia.core.websocket.pojo.WebSocketEvent;
import com.armundia.v2.shared.exception.ArmundiaException;

@Stateful
@ServerEndpoint(value = "/websocket", encoders = { MessageEncoder.class }, decoders = { MessageDecoder.class })
public class WebSocketEndpoint {
	private final Logger logger = Logger.getLogger(this.getClass().getName());

	@Inject
	private WebSocketApplication webSocketApplication;

	@Inject
	private WebSocket webSocket;
	

	public WebSocketEndpoint() {
		logger.log(Level.INFO, "INIT WEBSOCKET ENDPOINT");
	}

	@OnOpen
	public void onConnectionOpen(Session session) {
		logger.log(Level.INFO, "Connection open for {0}", session.getId());
		webSocketApplication.addSession(session);
	}

	@OnMessage
	public void onMessage(Session session, WebSocketEvent event) throws ArmundiaException {
		logger.log(Level.FINE, "Message Received from client: {0}", event);
		
		parseMessage(session, event);
	}

	@OnClose
	public void onConnectionClose(Session session) {
		logger.info("Connection close .... " + session.getId());
		webSocketApplication.removeSession(session);
	}
	
	
	@Inject
	private TestManager testWebSocket;
	
	/**
	 * From the message, calls the right method.
	 * NB: It does not allow @SessionScoped beans cause of the HTTP session is not shared throu the websocket. It allows @Stateful EJB beans.
	 * 
	 * @param session Client session
	 * @param event Event that contains
	 * @throws ArmundiaException
	 */
	private void parseMessage(Session session, WebSocketEvent event) throws ArmundiaException {
		SessionContainer sessionContainer = webSocketApplication.getSession(session);
		switch (event.message) {
			case "test":
				TestPojo data = webSocket.fromJson(event.data, TestPojo.class);
				testWebSocket.test(data, sessionContainer);
				break;
				
			default:
				logger.log(Level.WARNING, "Message not handled: {0}", event.message);
		}
	}
}
