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

import java.util.List;

import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.data.analysis.nlphub.shared.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.gcube.common.authorization.client.Constants.authorizationService;

public class DMDiscover {

	private static Logger logger = LoggerFactory.getLogger(DMDiscover.class);

	public DMDiscover() {

	}

	public String retrieveServiceUrl(String token) throws Exception {
		logger.debug("Retrieve DataMiner Service by token: " + token);
		String scope = retrieveScope(token);
		logger.debug("Retrieve DataMiner Service in scope: " + scope);
		String url = retrieveServiceInScope(scope);
		logger.debug("DataMiner url: " + url);
		return url;
	}

	private String retrieveServiceInScope(String scope) throws Exception {
		List<String> serviceAddress = InformationSystemUtils
				.retrieveServiceEndpoint(Constants.DATAMINER_SERVICE_CATEGORY, Constants.DATA_MINER_SERVICE_NAME, scope);
		logger.debug("Service Address retrieved:" + serviceAddress);
		if (serviceAddress == null || serviceAddress.size() < 1) {
			logger.error("No DataMiner service address available!");
			throw new Exception("No DataMiner service address available!");
		} else {
			logger.info("DataMiner service address found: " + serviceAddress.get(0));
			return serviceAddress.get(0);

		}
	}

	private String retrieveScope(String token) throws Exception {

		String userName = null;
		String scope = null;

		if (Constants.DEBUG) {
			logger.debug("Debug Mode");
			userName = Constants.DEFAULT_USER;
			scope = Constants.DEFAULT_SCOPE;
			token = Constants.DEFAULT_TOKEN;
		} else {
			logger.debug("Production Mode");
			if (token == null || token.isEmpty()) {
				logger.error("Error retrieving user credentials: token=" + token);
				throw new Exception("Error retrieving user credentials");
			}

			try {
				logger.debug("Retrieving user credentials");
				AuthorizationEntry entry = authorizationService().get(token);
				userName = entry.getClientInfo().getId();
				scope = entry.getContext();
			} catch (Exception e) {
				logger.error("Error retrieving user credentials: " + e.getLocalizedMessage());
				throw new Exception(e.getLocalizedMessage(), e);
			}

		}
		logger.debug("UserName: " + userName);
		logger.debug("Scope: " + scope);
		return scope;

	}

}
