package org.gcube.data.analysis.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.gcube.data.analysis.nlphub.is.DMDiscover;
import org.gcube.data.analysis.nlphub.session.SessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DiscoverDataMinerService() {
		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("Discover DataMinerService");
		SessionUtils sessionUtils=new SessionUtils();
		String token = sessionUtils.getToken(request);

		discoverDataMinerService(request, response, token);

	}

	private void discoverDataMinerService(HttpServletRequest request, HttpServletResponse response, String token)
			throws ServletException, IOException {

		String dataMinerServiceUrl = "";
		response.setContentType("text/plain;charset=UTF-8");
		try (PrintWriter writer = response.getWriter()) {
			DMDiscover dmDiscover = new DMDiscover();
			dataMinerServiceUrl = dmDiscover.retrieveServiceUrl(token);
			writer.println(dataMinerServiceUrl);

		} catch (Throwable e) {
			logger.error("Error discovering DataMiner Service Url: " + e.getLocalizedMessage(), e);
		}
	}
}
