package org.inria.bmajwatcher.server;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.inria.bmajwatcher.server.data.BankRetriever;

/**
 * Servlet that handles the requests from the client side datasource
 * to retrieve the list of the banks.
 * 
 * @author rsabas
 *
 */
public class BankListingService extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fetchData(resp.getWriter(), req);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fetchData(resp.getWriter(), req);
	}
	
	/**
	 * Retrieves the list of the banks and writes it as an XML message
	 * that follows the format required by <code>RestDataSource</code>.
	 * 
	 * @param out stream where output is written
	 * @param request request that contains parameters
	 */
	private void fetchData(PrintWriter out, HttpServletRequest request) {
		String biomajRoot = getServletContext().getInitParameter("BIOMAJ_ROOT");
		
		String type = getParameterValue(request, "type");
		String format = getParameterValue(request, "formats");
		String name = getParameterValue(request, "name");
		String release = getParameterValue(request, "release");
		String session = getParameterValue(request, "session");
		String status = getParameterValue(request, "status");
		String isGroup = getParameterValue(request, "group");
		String visibility = getParameterValue(request, "visibility");
		String isSched = getParameterValue(request, "isSched");
		String userKey = getParameterValue(request, "auth_key");
		
//		System.out.println("type:"+type+"// format:"+format+"// name:"+name+"// release:"+release+"// session:"+session+"// status:"+status+"// isgroup:"+isGroup+"// visibility:"+visibility+"// sched:"+isSched+"// userkey:" + userKey);
		
		out.write(BankRetriever.getInstance().getBankList(biomajRoot, type, format, name, release, session, status, isGroup, visibility, isSched, userKey));
		out.flush();
	}
	
	/**
	 * Returns parameter value in given request or empty string if parameter doesn't exist.
	 * 
	 * @param request
	 * @param name
	 * @return
	 */
	private static String getParameterValue(HttpServletRequest request, String name) {
		String value = request.getParameter(name);
		return value == null ? "" : value;
	}
	
	
}
