package com.rebelmonkey.monkeywrench.mweb;

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

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rebelmonkey.monkeywrench.mweb.api.MWeb;
import com.rebelmonkey.userinfo.MWUserInfo;
import com.sun.enterprise.web.connector.grizzly.comet.CometContext;
import com.sun.enterprise.web.connector.grizzly.comet.CometEngine;

/**
 * 
 * @author jeffpk
 */
public class MwebServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory
			.getLogger(MwebServlet.class);
	static final boolean DEBUGMODE = true;
	static final String SERVLETPREFIX = "__MWEB_";

	private String contextPath;

	@SuppressWarnings("unchecked")
	@Override
	public void init(ServletConfig config) throws ServletException {
		CometEngine engine = CometEngine.getEngine();
		CometContext cometContext = MWeb.getCometContext();
		cometContext.setExpirationDelay(30 * 1000);
	}

	// <editor-fold defaultstate="collapsed"
	// desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		CometClientHandler handler = (CometClientHandler) req.getSession()
				.getAttribute(SERVLETPREFIX + "clientHandler");
		if (handler == null) {
			handler = new CometClientHandler(MWUserInfo.getUserName(req
					.getSession()));
			req.getSession().setAttribute(SERVLETPREFIX + "clientHandler",
					handler);
		}
		handler.attach(res);
		CometEngine engine = CometEngine.getEngine();
		CometContext context = MWeb.getCometContext();
		context.addCometHandler(handler);
		if (req.getParameter("connectType").equals("connect")) {
			MWeb.sendConnectedMessage(MWUserInfo.getUserName(req.getSession()));
		}
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

	}

	/**
	 * Returns a short description of the servlet.
	 * 
	 * @return a String containing servlet description
	 */
	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>

}
