/* You may not modify, use, reproduce, or distribute this software except in compliance with the terms of the License at: 
 http://developer.sun.com/berkeley_license.html
 $Id: CometServlet.java,v 1.6 2007/07/14 07:14:30 gmurray71 Exp $ */

package com.sun.grizzly.comet;

import com.sun.enterprise.web.connector.grizzly.comet.CometContext;
import com.sun.enterprise.web.connector.grizzly.comet.CometEngine;
import com.sun.enterprise.web.connector.grizzly.comet.CometEvent;
import com.sun.enterprise.web.connector.grizzly.comet.CometHandler;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple Flickr Magnet Demo.
 *
 * @author Jeanfrancois Arcand
 * @author Greg Murray
 */
public class CometServlet extends HttpServlet{
    
    private static final long DEFAULT_EXPIRATION_DELAY = 60 * 6 * 1000;
    
    /**
     * The Comet enabled context-path
     */
    private String contextPath;

    /**
     * Simple counter
     */
    private int counter;
    
    public CometServlet() {
    }
    
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
                
        String cometUrlPattern = config.getInitParameter("cometUrlPattern");
        if (cometUrlPattern == null){
            cometUrlPattern = "/words";
        }
        
        // When the Servlet is initialized, tell Grizzly to dispatch
        // all matching requests to the CometEngine.
        contextPath = config.getServletContext().getContextPath() + cometUrlPattern;
        CometEngine cometEngine = CometEngine.getEngine();
        CometContext context = cometEngine.register(contextPath);
        
        String expire = config.getInitParameter("expirationDelay");
        if (expire == null) {
            context.setExpirationDelay(DEFAULT_EXPIRATION_DELAY);
        } else {
            context.setExpirationDelay(Long.parseLong(expire));
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doPost(request,response);
    }
    
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        String action = request.getParameter("action");
        CometEngine cometEngine = CometEngine.getEngine();
        CometContext cometContext = cometEngine.getCometContext(contextPath);
        
        if (action != null) {
            if ("post".equals(action)){
                String message = request.getParameter("message");
                String callback = request.getParameter("callback");
                if (callback== null) {callback = "alert";}
                
                // Notify other registered CometHandler.
                cometContext.notify("<script id='comet_" + counter++ + "'>"
                        + "window.parent." + callback + "(" +  message + ");</script>");              
                response.getWriter().println("ok");
                return;
            } else if ("start".equals(action)) {
                response.setContentType("text/html");
                String callback = request.getParameter("callback");
                if (callback== null) {callback = "alert";}
                
                String message = "{ message : 'Welcome'}";
                response.getWriter().println("<script id='comet_" + counter++ + "'>"
                        + "window.parent." + callback + "(" +  message + ");</script>");
                
                // Create and register a CometHandler.
                CometRequestHandler handler = new CometRequestHandler();
                handler.attach(response.getWriter());
                cometContext.addCometHandler(handler);
                return;
            }       
        }
    }
    
    // --------------------------------------------------------- Async Hook ---/
      
    
    public class CometRequestHandler implements CometHandler<PrintWriter>{
        
        protected PrintWriter printWriter;
                
        public void attach(PrintWriter printWriter){
            this.printWriter = printWriter;
        }
                
        public synchronized void onEvent(CometEvent event) throws IOException{
            try{                
                if (event.getType() != CometEvent.READ){
                    printWriter.println(event.attachment());
                    printWriter.flush();
                }
            } catch (Throwable t){
                t.printStackTrace();
            }
        }
        
        public void onInitialize(CometEvent event) throws IOException{
            printWriter.println("<html><head><title>jMaki Grizzly Comet Words Sample</title></head><body bgcolor=\"#FFFFFF\">");
            printWriter.flush();
        }
        
        public void onTerminate(CometEvent event) throws IOException{
            onInterrupt(event);
        }

        public void onInterrupt(CometEvent event) throws IOException{
            printWriter.println("jMaki Grizzly Comet Words Sample closed<br/>");
            printWriter.println("</body></html>");
            printWriter.flush();
            printWriter.close();
        }
    }
}