package gov.grants.apply.applicant.v2;

import java.util.List;

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

import gov.grants.apply.services.applicantwebservices_v2.ApplicantWebServicesPortType;
import gov.grants.apply.services.applicantwebservices_v2.GetOpportunitiesExpandedRequest;
import gov.grants.apply.services.applicantwebservices_v2.GetOpportunitiesExpandedResponse;
import gov.grants.apply.services.applicantwebservices_v2.GetOpportunityListRequest;
import gov.grants.apply.services.applicantwebservices_v2.GetOpportunityListResponse;
import gov.grants.apply.system.applicantcommonelements_v1.CFDADetails;
import gov.grants.apply.system.applicantcommonelements_v1.OpportunityDetails;
import gov.grants.apply.system.applicantcommonelements_v1.OpportunityFilter;

public class GetOpportunityListClient extends BaseApplicantClient {

	private static final String CLASSNAME = GetOpportunityListClient.class.getSimpleName();
	private static final Logger log = Logger.getLogger( CLASSNAME );
	
	
	/**
	 * @param args
	 */
	public static void main( String[] args ) {
		log.debug( "Begin " + CLASSNAME );
		
		try {
			GetOpportunityListClient client = new GetOpportunityListClient();
			
			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 cfdaNum = getArgMap().get( Globals.CFDA_NUM_CMD_LINE_KEY );
			log.debug( "Cfda Number: " + cfdaNum );
			
			String oppNum = getArgMap().get( Globals.OPP_NUM_CMD_LINE_KEY );
			log.debug( "Opportunity Number: " + oppNum );
			
			String compId = getArgMap().get( Globals.COMPETITION_ID_CMD_LINE_KEY );
			log.debug( "Competition ID: " + compId );
			
			String pkgId = getArgMap().get ( Globals.PKG_ID_CMD_LINE_KEY );
			log.debug( "Package ID: " + pkgId );
			
			
			ApplicantWebServicesPortType port = getApplicantPort();
			GetOpportunityListRequest request = new GetOpportunityListRequest();
			
			if( StringUtils.isNotEmpty( pkgId)) {
				request.setPackageID(pkgId);
			}
			
			// Create the Filter only if there one or more ofthe command line arguments are present...
			if( StringUtils.isNotEmpty( cfdaNum) || StringUtils.isNotEmpty( compId) || StringUtils.isNotEmpty( oppNum)) {
				OpportunityFilter oppFilter = new OpportunityFilter();
				oppFilter.setCFDANumber( cfdaNum);
				oppFilter.setCompetitionID( compId);
				oppFilter.setFundingOpportunityNumber( oppNum);
				request.setOpportunityFilter( oppFilter);
			}
			
			GetOpportunityListResponse response = port.getOpportunityList( request);
			List <OpportunityDetails> oppDetailsList = response.getOpportunityDetails();
			if( oppDetailsList != null && oppDetailsList.size() > 0) {	
				StringBuilder sb = new StringBuilder();
				for ( OpportunityDetails oppDetails : oppDetailsList ) {
					sb.append( "\n" );
					log.debug( ToStringBuilder.reflectionToString( oppDetails ) );
					sb.append( "\nFunding Opportunity Number: " ).append( oppDetails.getFundingOpportunityNumber());
					byte[] bytes = StringUtils.defaultString(oppDetails.getFundingOpportunityTitle()).getBytes("UTF-8"); 
					sb.append( "\nFunding Opportunity Title: " ).append( new String(bytes,"UTF-8") );
					sb.append( "\nPackage ID: " ).append( oppDetails.getPackageID());
					sb.append( "\nCompetition ID: " ).append( oppDetails.getCompetitionID() );
					sb.append( "\nCompetition Title: " ).append( oppDetails.getCompetitionTitle() );
					sb.append( "\nSchema URL: " ).append( oppDetails.getSchemaURL() );
					sb.append( "\nInstruction URL: " ).append( oppDetails.getInstructionsURL() );
					sb.append( "\nOffering Agency: " ).append( oppDetails.getOfferingAgency() );
					bytes = StringUtils.defaultString(oppDetails.getAgencyContactInfo()).getBytes("UTF-8"); 
					sb.append( "\nAgency Contact: " ).append( new String(bytes,"UTF-8") );
					sb.append( "\nIs Multi-Project: " ).append( oppDetails.isIsMultiProject() );

					sb.append( "\nOpening Date: " );
					log.debug("OpeningDate: "+oppDetails.getOpeningDate());
					if ( oppDetails.getOpeningDate() != null ) {
						sb.append( formatDate( oppDetails.getOpeningDate().toGregorianCalendar().getTime(), MMddyyyy ) );
					}// if
					sb.append( "\nClosing Date: " );
					log.debug("OpeningDate: "+oppDetails.getOpeningDate());
					if ( oppDetails.getClosingDate() != null ) {
						sb.append( formatDate( oppDetails.getClosingDate().toGregorianCalendar().getTime(), MMddyyyy ) );
					}// if

					if( oppDetails.getCFDADetails() != null && oppDetails.getCFDADetails().size() > 0 ) {
						sb.append( "\n****Total CFDA Numbers belongs to this opportunity =" + oppDetails.getCFDADetails().size());
						for( int i=0; i < oppDetails.getCFDADetails().size(); i++) {
							CFDADetails cfda = oppDetails.getCFDADetails().get( i);
							sb.append( "\n----------------------------------");
							sb.append( "\n--- CFDA Number: ").append( cfda.getNumber());
							bytes = StringUtils.defaultString(cfda.getTitle()).getBytes("UTF-8"); 
							sb.append( "\n--- CFDA Title: " ).append( new String(bytes,"UTF-8") );
							sb.append( "\n----------------------------------");
						}
					} else {
						sb.append( "\n****No CFDA Numbers belongs to this opportunity!");
					}
					sb.append( "\n**************************************************");
					sb.append( "\n\n" );
					
					log.debug( sb );
					sb.setLength( 0 );
					
					log.debug( "Total opportunity count found: " + oppDetailsList.size() );
				}// for
			} else {
				log.debug( "No opportunities found matching the input filters!");
			}
			
			
		} catch ( Exception e ) {
			log.error( "Exception: " + e.getMessage() );
			e.printStackTrace();
			throw e;
		}// try-catch
		
	}// makeServiceCall
	
}

