package org.gcube.application.cms.tests;

import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.common.utils.Files;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.authorization.utils.secret.GCubeSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.scope.api.ScopeProvider;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;

@Slf4j
public class TokenSetter {


    private static Properties props=new Properties();

    static{
        try {
            props.load(TokenSetter.class.getResourceAsStream("/tokens.properties"));
        } catch (Exception e) {
            throw new RuntimeException("YOU NEED TO SET TOKEN FILE IN CONFIGURATION",e);
        }
    }


    public static void set(String scope){
        SecretManagerProvider.instance.set(new SecretManager());
        if(!props.containsKey(scope)) throw new RuntimeException("No token found for scope : "+scope);
//			Secret secret = SecretUtility. getSecretByTokenString(token); // se non sai con che token hai a che fare;
        // oppure
        String toSet= props.getProperty(scope);
        log.debug("Setting secret "+toSet);
        Secret secret = new GCubeSecret(toSet); // se vecchio token
        // oppure
//			Secret secret = new JWTSecret(token); // se nuovo token

        SecretManagerProvider.instance.get().addSecret(secret);
        try{
            SecretManagerProvider.instance.get().set();
        }catch(Exception e ){throw new RuntimeException("Unable to set secret for context "+scope,e);}
    }
//
//		public static void setUma() throws IOException {
//			File umaFile = new File("uma.json");
//			String uma= Files.readFileAsString(umaFile.getAbsolutePath(), Charset.defaultCharset());
//			AccessTokenProvider.instance.set(uma);
//
//		}

}