

package gov.va.med.repositories.fpds.webservice;


import gov.va.med.repositories.fpds.filter.FilterBuilder;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import gov.va.med.repositories.fpds.validator.ValidationError;
import gov.va.med.repositories.fpds.validator.ValidationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.common.util.StringUtils;


public class FederatedPatientGeneratedDataRestService extends BaseParentFederatedPatientRestService
{
    
    Log logger = LogFactory.getLog( FederatedPatientGeneratedDataRestService.class );

    final static String DOMAIN="PatientGeneratedDataEvent";
    final static String DEFAULT_PGD_TEMPLATE = "PGDRead1";
    public static final String PATIENT_FILTER_KEY="PGD_SINGLE_PATIENT_FILTER";
    public static final String RECORD_IDENTIFIER_FILTER_KEY="PGD_UNIQUE_ID_FILTER";

    
    @GET
    @Path( "patient" )
    @Produces( { "application/json", "application/xml" } )
    public String readDataByPatient(@Context
    UriInfo uriInfo )
    {
        String result = null;
        String requestId = null;
        String templateId = null;
        MultivaluedMap<String, String> queryParameters = null;
        final String DOMAIN="PatientGeneratedDataEvent";
        String identifier = null;
        
        try
        {
            queryParameters = uriInfo.getQueryParameters();
            requestId = trimTrailingWhitespace(queryParameters.getFirst( REQUEST_ID ));
            templateId = getTemplateId(queryParameters, DEFAULT_PGD_TEMPLATE);
            
            identifier = queryParameters.getFirst( "nationalId" );
            if(identifier == null || StringUtils.isEmpty(identifier)){
            	identifier = queryParameters.getFirst( "resolvedIdentifier" );
            }
          
            result = processRead(templateId, requestId, null, PATIENT_FILTER_KEY, queryParameters);

        }
        catch ( Exception e )
        {
        	result = handleException(e, requestId, DOMAIN, templateId, identifier, queryParameters);
        }
 
        return result;
    }
    
    @GET
    @Path( "record/{identifier}" )
    @Produces( { "application/json", "application/xml" } )
    public String readDataByRecord(@PathParam( "identifier" )
    String identifier, @Context
    UriInfo uriInfo )
    {
        String result = null;
        String requestId = null;
        String templateId = null;
        MultivaluedMap<String, String> queryParameters = null;
       
        try
        {
            queryParameters = uriInfo.getQueryParameters();
            requestId = trimTrailingWhitespace(queryParameters.getFirst( REQUEST_ID ));
            templateId = getTemplateId(queryParameters, DEFAULT_PGD_TEMPLATE);
          
            result = processRead(templateId, requestId, identifier, RECORD_IDENTIFIER_FILTER_KEY, queryParameters);

        }
        catch ( Exception e )
        {
        	result = handleException(e, requestId, DOMAIN, templateId, identifier, queryParameters);
        }
 
        return result;
    }
    
    private String processRead(String templateId, String requestId, String identifier,  String defaultFilterId, MultivaluedMap<String, String> queryParameters)
    {
    	String result = null;
      
    	try
         {
    		 String filterId = getFilterId(queryParameters, defaultFilterId);
                                                             
             List<ValidationError> validationErrors = requestValidator.validateRequestParameters( filterId, queryParameters );

             if ( validationErrors != null && validationErrors.size() > 0 )
             {
                 throw new ValidationException( Status.BAD_REQUEST, validationErrors ); // indicates that the request being made was bad
             }
             
             FilterBuilder filtrBuilder = filterBuilderMap.get(filterId);
             if(filtrBuilder==null){
             	throw new ValidationException(Status.BAD_REQUEST,  requestValidator.constructValidationError( filterId, "Invalid Filter Id: " + filterId) );
             }
             
             String filterRequest = filtrBuilder.createFilter( filterId, identifier, DOMAIN, queryParameters );
             result = clinicalDataServiceWS.readClinicalData( templateId, filterRequest, filterId, requestId );

         }
         catch ( Exception e )
         {
        	 result = handleException(e, requestId, "GenericObservation", templateId, identifier, queryParameters);  
         }

         return result;
     }


}


