package com.javahonk;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * Servlet implementation class JQueryServlet
 */
@WebServlet("/JQueryServlet")
public class JQueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public JQueryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, 
	 * HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, 
			HttpServletResponse response) 
					throws ServletException, IOException {
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String processData = request.getParameter("processData");
		
		if (processData.equalsIgnoreCase("XML")) {
			response.setContentType("text/xml");
			response.setHeader("Cache-Control", "no-cache");
			response.getWriter().write("<details>");
			response.getWriter().write("<firstName>"
								+firstName+"</firstName>");
			response.getWriter().write("<lastName>"
								+lastName+"</lastName>");
			response.getWriter().write("</details>");
		} else {
			response.setContentType("application/json");
			response.setHeader("Cache-Control", "no-cache");
			Map<String, String> personMap = 
					new HashMap<String, String>();
			personMap.put("firstName", firstName);
			personMap.put("lastName", lastName);
			
			Gson gson = new GsonBuilder().setPrettyPrinting()
					.create();
		    String json = gson.toJson(personMap);
		    response.getWriter().write(json);
			
		}

		
	}

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

}
