package org.gcube.application.geoportal.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;

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

@Slf4j
public class ContextUtils {

	
	public static String getCurrentScope(){
		try{
			String token=SecurityTokenProvider.instance.get();
			log.trace("Token is : "+token.substring(0,2)+"..."+token.substring(token.length()-3));
			if(token==null) throw new Exception("Security Token is null");
			AuthorizationEntry entry = authorizationService().get(token);
			return entry.getContext();
		}catch(Exception e ){
			log.trace("Unable to resolve token, checking scope provider..",e);
			return ScopeProvider.instance.get();
		}
	}
	
	
	public static String getCurrentCaller(){
		try{
			String token=SecurityTokenProvider.instance.get();
			log.trace("Token is : "+token.substring(0,2)+"..."+token.substring(token.length()-3));
			if(token==null) throw new Exception("Security Token is null");
			AuthorizationEntry entry = authorizationService().get(token);
			return entry.getClientInfo().getId();
		}catch(Exception e ){
			log.trace("Unable to resolve token, checking scope provider..",e);
			return "Unidentified data-transfer user";
		}
	}
}
