package org.gcube.data.analysis.nlphub;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

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.gcube.data.analysis.nlphub.legacy.JsonManager;
import org.gcube.data.analysis.nlphub.nlp.RunnerCommander;
import org.gcube.data.analysis.nlphub.session.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet implementation class NLPHub
 */
@WebServlet(asyncSupported = true, name = "NLPServlet", urlPatterns = { "/nlphub-servlet" })
public class NLPHub extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(NLPHub.class);

	/**
	 * @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 {
		logger.debug("NLPHub");
		SessionUtils sessionUtils=new SessionUtils();
		String token = sessionUtils.getToken(request);

		if (request.getParameter("getInfo") != null) {
			getAlgorithmInfo(request, response, token);
		} else {
			runAlgorithms(request, response, token);
		}
		logger.debug("NLPHub work done");
	}

	private void getAlgorithmInfo(HttpServletRequest request, HttpServletResponse response, String token)
			throws ServletException {
		PrintWriter writer = null;
		try {
			logger.info("GetAlgorithmInfo");

			String dataMiner = request.getParameter("dataminer");
			String algId = request.getParameter("algId");
			logger.debug("NLPHub getAlgorithmInfo: [DataMiner=" + dataMiner + ", algorithmID=" + algId + "]");
			
			String algoLink = "https://services.d4science.org/group/rprototypinglab/data-miner?OperatorId=";
			algoLink=algoLink+algId;
			logger.debug("Algorithm link: "+algoLink);
			writer = response.getWriter();
			response.setContentType("application/json;charset=UTF-8");
			writer.println(new JsonManager().getSuccessJsonResponse(algoLink));
			
		} catch (Exception e) {
			logger.error("NLPHub error in GET AlgorithmInfo: " + e.getLocalizedMessage(), e);
			throw new ServletException("Error retrieving algorithm info!",e);
		} finally{
			if(writer!=null){
				writer.close();
			}
		}
	}

	private void runAlgorithms(HttpServletRequest request, HttpServletResponse response, String token)
			throws ServletException, IOException {
		try {
			String dataMiner = request.getParameter("dataminer");
			// dataMiner=java.net.URLDecoder.decode(dataMiner,"UTF-8");

			String[] algs = request.getParameter("algs").split(",");
			String plink = request.getParameter("plink");
			String annotations = request.getParameter("annotations");
			logger.debug("NLPHub getAlgorithmInfo: [DataMiner=" + dataMiner + ", plink=" + plink + ", annotations="
					+ annotations + ", algorithms=" + Arrays.toString(algs) + "]");

			for (int i = 0; i < algs.length; i++) {
				algs[i] = algs[i].trim();
			}

			String maxWaitingTime = getServletConfig().getInitParameter("MaxWaitingTime");
			String sleepTime = getServletConfig().getInitParameter("SleepTime");
			logger.debug("NLPHub: [maxWaitingTime=" + maxWaitingTime + ", sleepTime=" + sleepTime + "]");

			long maxWaitingTimeL = Long.parseLong(maxWaitingTime);
			long sleepTimeL = Long.parseLong(sleepTime);
			RunnerCommander commander = new RunnerCommander(dataMiner, algs, plink, annotations, token, response);
			commander.setSleepTime(sleepTimeL);
			commander.setMaxWaitingTime(maxWaitingTimeL);
			commander.startProcess();

		} catch (Exception e) {
			logger.error("NLPHub runAlgorithms: " + e.getLocalizedMessage(), e);
		}

	}
}
