package gov.grants.apply.applicant.v2;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ximpleware.VTDNav;

import gov.grants.apply.services.applicantwebservices_v2.ApplicantWebServicesPortType;
import gov.grants.apply.services.applicantwebservices_v2.AuthenticateAORExpandedRequest;
import gov.grants.apply.services.applicantwebservices_v2.AuthenticateAORExpandedResponse;
import gov.grants.apply.system.grantscommonelements_v1.SecurityMessage;
import gov.grants.apply.system.grantscommonelements_v1.TokenInfo;
import gov.grants.apply.system.grantscommontypes_v1.AORStatusType;

public class AuthenticateAORExpandedClient extends BaseApplicantClient {

	private static final String CLASSNAME = AuthenticateAORExpandedClient.class.getSimpleName();
	private static final Logger log = Logger.getLogger( CLASSNAME );
	
	
	/**
	 * @param args
	 */
	public static void main( String[] args ) {
		log.debug( "Begin " + CLASSNAME );
		
		try {
			AuthenticateAORExpandedClient client = new AuthenticateAORExpandedClient();
			
			log.debug( "args length: " + args.length );
			client.init( args );
			
			client.makeServiceCall();
			log.debug( "\n\nSUCCESS: " + CLASSNAME + " successfully completed" );

		} catch ( Exception e ) {
			log.error( "\n\nException: " + e.getMessage() );
		}// try-catch
		
	}// main
	
	
	public void makeServiceCall() throws Exception {
		try {
			
			String aorUserId = null;
			String aorPassword = null;
			String aorDuns = null;
			String aorUei = null;
			
			
			String configXml = getArgMap().get( Globals.CONFIG_XML_CMD_LINE_KEY );
			loadConfigXmlDoc( configXml );
			configVN.toElement( VTDNav.FIRST_CHILD, CLASSNAME );// navigate to client element
			
			if ( configVN.toElement( VTDNav.FIRST_CHILD, Globals.AOR_USER_ID_ELEMENT_NAME )) {
				aorUserId = configVN.toNormalizedString( configVN.getText() );
				log.debug( "aorUserId: " + aorUserId );
				configVN.toElement( VTDNav.PARENT );
			}
			
			
			if( configVN.toElement( VTDNav.FIRST_CHILD, Globals.AOR_PASSWORD_ELEMENT_NAME )) {
				aorPassword = configVN.toNormalizedString( configVN.getText());
				log.debug( "aorPassword: " + aorPassword );
				configVN.toElement( VTDNav.PARENT );
				
			}
			
			if( configVN.toElement( VTDNav.FIRST_CHILD, Globals.AOR_DUNS_ELEMENT_NAME )) {
				aorDuns = configVN.toNormalizedString( configVN.getText() );
				log.debug( "aorDuns: " + aorDuns );
				configVN.toElement( VTDNav.PARENT );
			} else {
				log.debug( "Optional AOR DUNS is not specified!");
			}
			
			if( configVN.toElement( VTDNav.FIRST_CHILD, Globals.AOR_UEI_ELEMENT_NAME )) {
				aorUei = configVN.toNormalizedString( configVN.getText() );
				log.debug( "aorUei: " + aorUei );
				configVN.toElement( VTDNav.PARENT );
			} else {
				log.debug( "Optional AOR UEI is not specified!");
			}
			
			if ( StringUtils.isBlank( aorUserId ) || StringUtils.isBlank( aorPassword )) {
				String s = "aor-user-id and aor-password elements in the config xml cannot be blank";
				log.error( s );
				throw new Exception( s );
			}// if
			
			ApplicantWebServicesPortType port = getApplicantPort();
			
			AuthenticateAORExpandedRequest request = new AuthenticateAORExpandedRequest();
			request.setAORUserID( aorUserId );
			request.setAORPassword( aorPassword );
			request.setDUNS( aorDuns);
			request.setUEI( aorUei);
			
			AuthenticateAORExpandedResponse response = port.authenticateAORExpanded( request );
			StringBuilder sb = new StringBuilder();
			
			if( response.getAORStatus() == AORStatusType.AUTHORIZED ) {
				sb.append( "\n\n" )
				.append( "AuthenticateAORExpandedResponse Information: " )
				.append( "\n==========" )
				.append( "\nAOR Status: " + response.getAORStatus() )
				.append( "\nAOR User Full Name: " + response.getAORUserFullName());
				TokenInfo info = response.getTokenInfo();
				if( info != null) {
					sb.append( "\nTokenInfo Information:");
					sb.append( "\n----------" );
					sb.append( "\nToken ID: " + info.getTokenID());
					sb.append( "\nToken Expiration Date: " + info.getTokenExpirationDate());
				} else {
					sb.append( "\n\nTokenInfo is blank" );
				}
				
			} else { // Failed to Authorize attempt to get the Error Message Details:
				SecurityMessage msg = response.getSecurityMessage();
				if ( msg != null ) {
					sb.append( "\n\n" )
					.append( "SECURITY MESSAGE INFO" )
					.append( "\n=====================" )
					.append( "\nMessage Code: " + msg.getMessageCode() )
					.append( "\nMessage Text: " + msg.getMessageText() );
				} else {
					sb.append( "\n\nSecurity message is blank" );
					
				}// if-else
			}
			sb.append( "\n\n" );
			log.debug( sb );

		} catch ( Exception e ) {
			log.error( "Exception: " + e.getMessage() );
			e.printStackTrace();
			throw e;
		}// try-catch
		
	}// makeServiceCall
	
}

