/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import com.sun.grizzly.comet.CometContext;
import com.sun.grizzly.comet.CometEngine;
import com.sun.grizzly.cometd.bayeux.Data;
import com.sun.grizzly.cometd.bayeux.DeliverResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple Servlet that update the Chat application via a simple Http request
 *
 * <code>
 * http://localhost:port/cometd/ChatExternalServlet?user=me&message=hello
 * </code>
 *
 * @author Doris Chen
 */
public class ChatExternalServlet extends HttpServlet {


    /**
    * All request to that channel will be considered as cometd enabled.
    */
     private String channel ="/chat/demo";

    /**
     * Push message on the chat room every 10 seconds.
     */
    public ScheduledThreadPoolExecutor timer =
            new ScheduledThreadPoolExecutor(1);

    /**
     * Initialize the Servlet by creating the CometContext.
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        if (config.getInitParameter("channel") != null){
             channel = config.getInitParameter("channel");

        }

        timer.scheduleAtFixedRate(new Runnable(){
                public void run(){
                    CometEngine engine = CometEngine.getEngine();
                    CometContext context = engine.getCometContext(channel);

                    if (context != null) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("text", "Wake up call form the chatroom :-)");
                        map.put("user", "ChatMonitor");
                        Data data = new Data();
                        data.setMapData(map);

                        DeliverResponse deliverResponse = new DeliverResponse();
                        deliverResponse.setChannel(channel);
                        deliverResponse.setData(data);
                        deliverResponse.setLast(true);
                        deliverResponse.setFollow(true);
                        deliverResponse.setFinished(true);
                        try{
                            context.notify(deliverResponse);

                        } catch(IOException ex){
                            ex.printStackTrace();
                        }
                    }
                }
            }, 10, 10, TimeUnit.SECONDS);

    }

   @Override
   public void destroy(){
       timer.shutdown();
   }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * See
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // message and user are part of the simple HTTP request will invoke late.
        String message = request.getParameter("message");
        String user = request.getParameter("user");
        ServletOutputStream out = response.getOutputStream();

        //create the comet context with the specified channel.
        CometEngine engine = CometEngine.getEngine();
        CometContext context = engine.getCometContext(channel);

        if (context != null && message != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            // text and user are defined entry in the previous chat application.
            map.put("text", message);
            map.put("user", user);

            //Construct a Bayeux response message using Data and DeliverResponse.
            Data data = new Data();
            data.setMapData(map);
            

            DeliverResponse deliverResponse = new DeliverResponse();
            deliverResponse.setChannel(channel);
            deliverResponse.setData(data);
            deliverResponse.setLast(true);
            deliverResponse.setFollow(true);
            deliverResponse.setFinished(true);

            //send the Bayeux message out by invoking notify().
            context.notify(deliverResponse);

            out.println("Data is sent.");
            
        } else {
            out.println("No data is sent.");
        }
    }
}
