package gov.va.vinci.dart.db;

import gov.va.vinci.dart.biz.RequestSummary;
import gov.va.vinci.dart.biz.WorkflowSummary;
import gov.va.vinci.dart.db.impl.RequestSummaryBuilder;
import gov.va.vinci.dart.db.util.CallableStatementDAO;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AllParticipantRequestsDAO extends CallableStatementDAO<RequestSummary> {
	private String userId;
	RequestSummaryBuilder builder = new RequestSummaryBuilder();
	
	public AllParticipantRequestsDAO(final String userId) {
		this.userId = userId;
	}
	
	public String getQueryText() {
		return "{call [ws].[GetDARTDashboardRequestsByUser](?)}";	//get the requests for this participant or requestor
	}
	
	public void populateParameters(final CallableStatement cstmt) throws SQLException {
		cstmt.setString(1, userId);
	}
	
	public RequestSummary buildResult(final ResultSet rs) throws SQLException {
        return builder.build(rs);
	}

	
	/**
	 * Collapse the output of the query, for each request.
	 */
	@Override
	public List<RequestSummary> build() throws SQLException {
		
		List<RequestSummary> result = new ArrayList<RequestSummary>();
		
		CallableStatement cstmt = createCallableStatement(getQueryText());
		populateParameters(cstmt);
	
		ResultSet rs = cstmt.executeQuery();
		
		if( rs != null ) {

			String currentTrackingNumber = "";
			
			while (rs.next()) {
				
				RequestSummary currentRequest = buildResult(rs);
				if( currentRequest != null && currentRequest.getTrackingNumber() != null ) {

					if( currentRequest.getTrackingNumber().equalsIgnoreCase( currentTrackingNumber ) == false ) {	//new tracking number, so add this request to the list
						result.add( currentRequest );	//add the new entry to the list (new tracking number)
						currentTrackingNumber = currentRequest.getTrackingNumber();	//remember the new tracking number
					} else {	//same tracking number

						if( currentRequest.getWorkflowSummaryList() != null && currentRequest.getWorkflowSummaryList().size() > 0 ) {

							WorkflowSummary workflowSummaryToCopy = currentRequest.getWorkflowSummaryList().get(0);
							if( workflowSummaryToCopy != null ) {

								WorkflowSummary workflowSummary = new WorkflowSummary( workflowSummaryToCopy );


								int index = result.size() - 1;	//last entry in the list
								result.get(index).getWorkflowSummaryList().add( workflowSummary );	//add the workflow details to the existing entry

							}//end if
						}//end if

					}//end else
				}//end if
			}//end while
		}

		return result;
	}
	
}
