package org.gcube.contentmanager.storageserver.utils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.util.Objects;

import org.gcube.common.authorization.library.provider.UmaJWTProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.oidc.rest.JWTToken;
import org.gcube.oidc.rest.OpenIdConnectRESTHelper;
import org.gcube.oidc.rest.OpenIdConnectRESTHelperException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Utils {
	
	private static final Logger logger = LoggerFactory.getLogger(Utils.class);
	
	public static  JWTToken setToken(URL oidcAddress, String clientId, String secret) throws OpenIdConnectRESTHelperException {
		JWTToken token=null;
		String context=ScopeProvider.instance.get();
		try {
			logger.trace("setToken method");
			
			logger.trace("we are in "+context);
			if((!Objects.isNull(context)) && (!Objects.isNull(clientId))&& (!Objects.isNull(secret))) {
				logger.info(clientId+" getting the UMAtoken for context "+context);	
				logger.debug("from "+oidcAddress);
				token = OpenIdConnectRESTHelper.queryUMAToken(oidcAddress, clientId, secret, context, null);
				logger.debug("UMA token retrieved for context "+context);
				String tokenExtracted=getTokenFromJson(token);
				UmaJWTProvider.instance.set(tokenExtracted);				
			}else {
				logger.error("problem initializing token, one or more field not set");
				throw new RuntimeException("problem initializing token, one or more field not set");
			}
		}catch(Throwable t) {
			logger.error("Exception: ", t);
			throw new RuntimeException("Problem with tokens in context"+context+" ", t);
		}
		return token;
	}
	
	public static String getTokenFromJson(JWTToken jwtToken) {
		logger.debug("extracting token from json");
		JSONParser parser= new JSONParser();
		String token=null;
		try {
			Reader reader= new StringReader(jwtToken.toString());
			JSONObject jsonObject = (JSONObject) parser.parse(reader);
			token = (String) jsonObject.get("access_token");
			logger.info("access token for context "+ScopeProvider.instance.get()+" retrieved");
		} catch (IOException e) {
			logger.error("IOEXception", e);
            e.printStackTrace();
        } catch (ParseException e) {
        	logger.error("ParseException", e);
            e.printStackTrace();
        }
		return token;
	}

}
