package org.jboss.as.jacorb.security;

import org.jboss.metadata.ejb.jboss.IORSecurityConfigMetaData;
import org.jboss.metadata.ejb.jboss.IORTransportConfigMetaData;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;

/**
 * @author <a href="mailto:tadamski@redhat.com">Tomasz Adamski</a>
 */
public class SSLRequiredService implements Service<Boolean>{

    public static final ServiceName SSL_REQUIRED_SERVICE_NAME = ServiceName.JBOSS.append("security").append("iiop").append("ssl-required");

    private final boolean serverAuthRequired;
    private final InjectedValue<IORSecurityConfigMetaData> iorSecConfigMetaDataValue = new InjectedValue<IORSecurityConfigMetaData>();

    /**
     * Server authentication requirement (definied in the jacorb subsystem).
     */
    private Boolean sslRequired;

    public SSLRequiredService(final boolean serverAuthRequired){
        this.serverAuthRequired = serverAuthRequired;
    }


    @Override
    public void start(final StartContext startContext) throws StartException {
        final IORSecurityConfigMetaData iorSecurityConfigMetaData = iorSecConfigMetaDataValue.getOptionalValue();
        // Create SSLPolicy (SSL_REQUIRED ensures home and remote IORs will have port 0 in the primary address).
        if (serverAuthRequired) {
            sslRequired = true;
        } else if (iorSecurityConfigMetaData != null && iorSecurityConfigMetaData.getTransportConfig() != null) {
            final IORTransportConfigMetaData tc = iorSecurityConfigMetaData.getTransportConfig();
            sslRequired = IORTransportConfigMetaData.INTEGRITY_REQUIRED.equals(tc.getIntegrity())
                    || IORTransportConfigMetaData.CONFIDENTIALITY_REQUIRED.equals(tc.getConfidentiality())
                    || IORTransportConfigMetaData.ESTABLISH_TRUST_IN_CLIENT_REQUIRED.equals(tc.getEstablishTrustInClient());
        } else {
            sslRequired = false;
        }
    }

    @Override
    public void stop(final StopContext stopContext) {

    }

    @Override
    public Boolean getValue() throws IllegalStateException, IllegalArgumentException {
        return sslRequired;
    }
}
