package gov.va.med.edp.weblogic;


import java.security.cert.X509Certificate;

import org.apache.log4j.Logger;

import weblogic.security.providers.authentication.UserNameMapper;

public class EDPUserNameMapper implements UserNameMapper {

												  
    private static Logger logger = Logger.getLogger(EDPUserNameMapper.class);

	public String mapCertificateToUserName(X509Certificate[] certs, boolean ssl) {
		String machineName = "";

		
		if (certs.length > 0) {
			String dn = certs[0].getSubjectDN().getName();
			if (logger.isDebugEnabled()){
				logger.debug("Certificate Contents: " + dn);
			}
			String[] parts = dn.split(",");
			for (int i = 0; i < parts.length; i++) {
				String dName = parts[i];
				if (dName.indexOf("CN=") != -1){
					machineName = dName.trim().substring(3);
				}

				if (machineName.length() == 0){
					throw new IllegalStateException("Machine Name obtained from the client SSL Certificate is not valid. The machine name was empty");
				}

				WeblogicUserManager.addUserToWeblogicSecurity(machineName);

				if (logger.isDebugEnabled()){
					logger.debug("SUCCESS!!...Returning Machine Name: '" + machineName + "' for Weblogic Security");
				}
				
				return machineName;
			}
				
		}
		return "INVALID_USER";
	}
	

	public String mapDistinguishedNameToUserName(byte[] arg0) {
		throw new UnsupportedOperationException("The method 'mapDistinguishedNameToUserName' in class " + getClass().getName() + " is not supported");
	}

	

	
	
}
