/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.kiwi.cometd.websocket;

import cz.kiwi.cometd.websocket.protocol.WebSocketKiwiActivityProtocol;
import cz.kiwi.cometd.websocket.protocol.WebSocketKiwiCommandProtocol;
import cz.kiwi.cometd.websocket.protocol.WebSocketKiwiContentProtocol;
import cz.kiwi.cometd.websocket.protocol.WebSocketKiwiLogProtocol;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketFactory;

public class WebSocketJettyServlet extends HttpServlet
{
  private WebSocketFactory _wsFactory;
  
  public static WebSocketKiwiContentProtocol webSocketKiwiContentProtocol; //prepsat
  public static WebSocketKiwiCommandProtocol webSocketKiwiCommandProtocol; //prepsat
 
  @Override
  public void init() throws ServletException {
     //Create and configure WS factory
    _wsFactory=new WebSocketFactory(new WebSocketFactory.Acceptor()
    {
      public boolean checkOrigin(HttpServletRequest request, String origin) {
        // Allow all origins
        return true;
      }
 
      public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
      {
         if ("activity".equals(protocol))
           return new WebSocketKiwiActivityProtocol();
         else if ("log".equals(protocol))
           return new WebSocketKiwiLogProtocol();
         else if ("content".equals(protocol)) {
             webSocketKiwiContentProtocol = new WebSocketKiwiContentProtocol();
             return webSocketKiwiContentProtocol;
         }
         else if ("command".equals(protocol)) {
             webSocketKiwiCommandProtocol = new WebSocketKiwiCommandProtocol();
             return webSocketKiwiCommandProtocol;
         }
         
         return null;
      }      
    });
    
    _wsFactory.setBufferSize(32768);
    _wsFactory.setMaxIdleTime(0);
  }
  
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (_wsFactory.acceptWebSocket(request,response)) {
            System.out.println("Accepting websocket");
            return;
        }
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Websocket only");
  }
}
