/**
 * 
 */


package gov.va.med.cds.response.strategy;


import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.filter.EntryFilterInterface;
import gov.va.med.cds.persistence.PersistenceException;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;


/**
 * @author DNS   kondas
 * 
 * <p>In some cases, the VistA Generic Stored Procedure responds with multiple records that
 * constitutes a single result from the VistAa system. The result is split between multiple
 * records due to limitation that Cache / MUMPS systems have with regard to string lengths.
 * 
 * <p>This response strategy object assumes that all of the records passed into the format
 * response method are a single record and concatenates the response prior to sending it on. 
 *
 */
public class VistaGenericStoredProcedureJsonResponseStrategy

{

    public String processJsonFilter( String records, EntryFilterInterface entryFilter )
    {

        JSONObject response = null;

        JSONParser jsonparser = new JSONParser( -1 );
        try
        {
            response = ( JSONObject )jsonparser.parse( records );
        }
        catch ( ParseException e )
        {
            throw new PersistenceException( ErrorCodeEnum.INVALID_JSONPATH_QUERY, e.getMessage() );
        }

        JSONObject dataObj = ( JSONObject )response.get( "data" );
        dataObj.remove( "totalItems" );
        dataObj.remove( "items" );

        ReadContext ctx = JsonPath.parse( records );
        JSONArray filterdResponse = ctx.read( entryFilter.getJsonPathQuery() );

        int nbrItems = filterdResponse.size();
        dataObj.put( "items", filterdResponse );
        dataObj.put( "totalItems", nbrItems );

        return response.toString();

    }

}
