package dev.rusatom.keycloak.modules.esia;

import java.util.Arrays;
import java.util.stream.Collectors;

import org.jboss.logging.Logger;
import org.keycloak.broker.oidc.OAuth2IdentityProviderConfig;
import org.keycloak.models.IdentityProviderModel;

import dev.rusatom.keycloak.modules.Signer;
import dev.rusatom.keycloak.modules.SignerFactory;

/**
 * Настройки OAuth-авторизации через <a href="https://esia.gosuslugi.ru/">ЕСИА</a>.
 *
 * @author Ivan Kovalenko
 */
public class EsiaIdentityProviderConfig extends OAuth2IdentityProviderConfig {

    /**
	 * 
	 */
	private static final long serialVersionUID = -3508282207240630771L;
	protected static final Logger logger = Logger.getLogger(EsiaIdentityProviderConfig.class);

    /**
     * Создает объект настроек OAuth-авторизации через
     * <a href="https://esia.gosuslugi.ru/">ЕСИА</a>.
     *
     * @param model Модель настроек OAuth-авторизации.
     */
	private static final String ESIA_2_65_SCOPES = "openid fullname birthdate id_doc gender snils inn email mobile contacts vehicles usr_avt usr_org kid_fullname kid_birthdate kid_gender kid_snils kid_inn kid_birth_cert_doc org_shortname org_fullname org_type org_ogrn org_inn org_leg org_kpp org_vhls org_ctts org_addrs";

	public EsiaIdentityProviderConfig(IdentityProviderModel model) {
        super(model);
    }
	
	// To be used when constructing authorization url  
	@Override
	public String getDefaultScope() {
		String scope = getAllScopes();
		return getPersonScopes(scope);
	}
	
	public String getAllScopes() {
		logger.debug("Scopes defined in UI : " + super.getDefaultScope());
		return super.getDefaultScope();
	}
	public String getPersonScopes(String scope) {
    	String resultingScope = Arrays.stream(scope.split(" ")).filter(e -> e.startsWith("org_")?false:true).collect(Collectors.joining(" "));
    	return resultingScope;
		
	}
    public String getPersonScopes() {
    	String scope = getAllScopes();
    	return getPersonScopes(scope);
    }

    public String getOrgScopes() {
    	String scope = getAllScopes();
    	String resultingScope = Arrays.stream(scope.split(" ")).filter(e -> e.startsWith("org_")?true:false).collect(Collectors.joining(" "));
    	return resultingScope;
    }

	static final String ESIA_TEST_URL = "https://esia-portal1.test.gosuslugi.ru";
	static final String ESIA_URL = "https://esia.gosuslugi.ru";

    
    public String getEsiaUrl() {
    	String env = System.getenv("ESIA_ENV");
    	if(env!=null && env.equals("PROD")) {
    		return ESIA_URL;
    	}
    	return ESIA_TEST_URL;
    }
    @Override
    public boolean isStoreToken() {
		return true;

    }
    
    public Signer getSigner() {
    	String type = System.getenv("ESIA_SIGNER");
    	return SignerFactory.getSigner(type);
    }
}
