package org.gcube.data.analysis.nlphub.session;

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

import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.data.analysis.nlphub.shared.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SessionUtils {
	private static final Logger logger = LoggerFactory.getLogger(SessionUtils.class);

	public String getToken(HttpServletRequest request) throws ServletException {
		String token = request.getParameter(Constants.TOKEN_PARAMETER);
		logger.debug("Token in request: " + token);
		if (token == null || token.isEmpty()) {
			logger.debug("Token is null");
			throw new ServletException("Token is null");
		}

		setAuth(token);
		return token;
	}

	private void setAuth(String token) throws ServletException {
		try {
			SecurityTokenProvider.instance.set(token);
			AuthorizationEntry authorizationEntry = org.gcube.common.authorization.client.Constants
					.authorizationService().get(token);
			ClientInfo clientInfo = authorizationEntry.getClientInfo();
			logger.debug("User : {} - Type : {}", clientInfo.getId(), clientInfo.getType().name());
			String qualifier = authorizationEntry.getQualifier();
			Caller caller = new Caller(clientInfo, qualifier);
			AuthorizationProvider.instance.set(caller);
			ScopeProvider.instance.set(authorizationEntry.getContext());
		} catch (Exception e) {
			logger.error("Error in set context: " + e.getLocalizedMessage(), e);
			throw new ServletException("Error in set context: " + e.getLocalizedMessage(), e);
		}
	}

	/*
	 * private static void checkToken(String token) throws Exception { if (token
	 * == null || token.isEmpty()) { logger.error("Token is null"); throw new
	 * Exception("Token is null"); } else { AuthorizationEntry entry;
	 * 
	 * entry = authorizationService().get(token); ClientInfo clientInfo =
	 * entry.getClientInfo(); if (clientInfo == null) {
	 * logger.error("User not found."); throw new
	 * Exception("Authorization failed!"); } else { logger.debug("User: " +
	 * clientInfo.getId()); String context = entry.getContext();
	 * logger.debug("Context: " + context); }
	 * 
	 * }
	 * 
	 * }
	 */

}
