package org.gcube.nlphub;

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

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 org.apache.log4j.Logger;
import org.gcube.nlphub.legacy.Constants;
import org.gcube.nlphub.legacy.JsonManager;
import org.gcube.nlphub.nlp.RunnerCommander;

/**
 * Servlet implementation class NLPHub
 */
@WebServlet(asyncSupported = true, name = "NLPServlet", urlPatterns = { "/nlphub-servlet" })
public class NLPHub extends HttpServlet {
	private Logger logger = Logger.getLogger(NLPHub.class.getSimpleName());
	private static final long serialVersionUID = 1L;
	public static final String service = "http://dataminer-prototypes.d4science.org/wps/";
	private String token; //= "df2cc5f5-63ee-48c1-b2a6-1210030c57b8-843339462";
	private boolean devMode = true;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NLPHub() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doWork(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doWork(request, response);
	}

	private void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		token = Constants.getToken(request, devMode);
		try {
			String dataMiner = request.getParameter("dataminer");
			String[] algs = request.getParameter("algs").split(",");
			for(int i=0; i<algs.length; i++) {
				algs[i] = algs[i].trim();
			}
			
			
			RunnerCommander commander = new RunnerCommander(dataMiner, algs, request.getParameter("plink"), request.getParameter("annotations"), token,
					 response);
			commander.setSleepTime(100);
			commander.setMaxWaitingTime(90*1000);
			commander.startProcess();

		} catch (Exception x) {
			x.printStackTrace();
		}

	}
}
