package br.com.centralit.websocket.server;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebServlet;

import br.com.centralit.websocket.jboss.as.websockets.WebSocket;
import br.com.centralit.websocket.jboss.as.websockets.servlet.WebSocketServlet;
import br.com.centralit.websocket.jboss.websockets.Frame;
import br.com.centralit.websocket.jboss.websockets.frame.TextFrame;

@SuppressWarnings("serial")
@WebServlet("/websocket")
public class MyWebSocketServlet extends WebSocketServlet {
	public static Map<String, WebSocket> sockets = new HashMap<String, WebSocket>();

	@Override
	protected void onSocketOpened(WebSocket socket) throws IOException {
		System.out.println("Websocket opened [" + socket.getSocketID() + "]");

		MyWebSocketServlet.sockets.put(socket.getSocketID(), socket);
	}

	@Override
	protected void onSocketClosed(WebSocket socket) {
		MyWebSocketServlet.sockets.remove(socket.getSocketID());
		System.out.println("Websocket closed [" + socket.getSocketID() + "]");
	}

	@Override
	protected void onReceivedFrame(String socketID, Frame frame) {
		try {
			System.out.println("Got a frame [" + frame + "] from socket [" + socketID + "]");

			String text = ((TextFrame) frame).getText();

			System.out.println("Got message " + text);

			for (Map.Entry<String, WebSocket> entry : sockets.entrySet()) {
				try {
					entry.getValue().writeFrame(TextFrame.from(text));
				} catch (Exception e) {
					System.out.println("Issue writing frame: " + e.getMessage());
				}
			}
		} catch (Exception ex) {
			System.out.println("Issue reading frame: " + ex.getMessage());
		}
	}
}
