package com.rebelmonkey.mweb.test;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rebelmonkey.monkeywrench.mweb.api.MWeb;
import com.rebelmonkey.userinfo.MWUserInfo;

/**
 * Servlet implementation class ChatTestServlet
 */
public class ChatTestServlet extends HttpServlet {
	private static final Logger logger = LoggerFactory.getLogger(ChatTestServlet.class);
	private static final long serialVersionUID = 1L;
	private static final String PUBLICCHANNEL = "ChatTest_public";
    /**
     * Default constructor. 
     */
    public ChatTestServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		HttpSession session = request.getSession();
		String userName = MWUserInfo.getUserName(session);
		logger.info("Got action "+action+" from user "+userName);
		if (action.equals("joinChat")){
			logger.info("doing JoinChat stuff");
			MWeb.addUserToChannel(userName, PUBLICCHANNEL);
			try{
				Thread.sleep(500);
			} catch (Exception e){
				logger.error("sleep error",e);
			}
			MWeb.sendChannelPacket("<server>", PUBLICCHANNEL,makePacket("action","userJoin","userName",userName));
			logger.info("done joinchat stuff");
		} else if (action.equals("leaveChat")){ 
			MWeb.removeUserFromChannel(userName, PUBLICCHANNEL);
			MWeb.sendChannelPacket("<server>", PUBLICCHANNEL,
					makePacket("action","userLeave","userName",userName));
		} else if (action.equals("publicMessage")){
			MWeb.sendChannelPacket(userName, PUBLICCHANNEL, 
					makePacket("action","publicMessage","message",request.getParameter("message")));
		} else if (action.equals("privateMessage")){
			MWeb.sendPrivatePacket(userName, request.getParameter("to"), 
					makePacket("action","privateMessage","message",request.getParameter("message")));
		}
	}
 
	private String makePacket(String ...strings ) throws IOException {
		StringWriter writer = new StringWriter();
		JsonGenerator gen = new JsonFactory().createJsonGenerator(writer);
		gen.writeStartObject();
		for(int i =0; i<strings.length;i+=2){
			gen.writeStringField(strings[i], strings[i+1]);
		}
		gen.writeEndObject();
		gen.flush();
		writer.flush();
		gen.close();
		return writer.toString();
	}
	
	
}
