package org.keycloak.adapters.springsecurity;

import org.keycloak.adapters.AdapterDeploymentContext;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.KeycloakDeploymentBuilder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;

import java.io.InputStream;

/**
 * Bean holding the {@link KeycloakDeployment} and {@link AdapterDeploymentContext} for this
 * Spring application context. The Keycloak deployment is loaded from the required
 * <code>WEB-INF/keycloak.json</code> file generated by Keycloak.
 *
 * @author <a href="mailto:srossillo@smartling.com">Scott Rossillo</a>
 * @version $Revision: 1 $
 */
public class AdapterDeploymentContextBean implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;
    private AdapterDeploymentContext deploymentContext;
    private KeycloakDeployment deployment;

    @Override
    public void afterPropertiesSet() throws Exception {
        Resource resource = applicationContext.getResource("WEB-INF/keycloak.json");
        InputStream is = resource.getInputStream();
        this.deployment = KeycloakDeploymentBuilder.build(is);
        this.deploymentContext = new AdapterDeploymentContext(deployment);
    }

    /**
     * Returns the Keycloak {@link AdapterDeploymentContext} for this application context.
     *
     * @return the Keycloak {@link AdapterDeploymentContext} for this application context
     */
    public AdapterDeploymentContext getDeploymentContext() {
        return deploymentContext;
    }

    /**
     * Returns the {@link KeycloakDeployment} for this application context.
     *
     * @return the {@link KeycloakDeployment} for this application context
     */
    public KeycloakDeployment getDeployment() {
        return deployment;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
