

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


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;


public class AppointmentLetterBlobStrategy
    extends
        ReferenceMappingVistaResponseBlobStrategy
{

    @Override
    public Element formatResponse( List<Map<String, Object>> resultList, String domainEntryPoint, String templateId )
        throws Exception
    {

        Element results = DocumentHelper.createElement( "results" );

        results.addElement( "appointmentLetter" );

        Element appointmentLetter = results.element( "appointmentLetter" );

        Document testDocument = DocumentHelper.parseText( extractAppointLetterBlobData( resultList ) );

        List<Element> blobElementList = testDocument.getRootElement().elements();

        for ( Element blobElement : blobElementList )
        {
            appointmentLetter.add( blobElement.detach() );
        }

        return appointmentLetter;
    }


    private String extractAppointLetterBlobData( List<Map<String, Object>> resultList )
        throws IOException
    {

        BufferedReader reader = new BufferedReader( new InputStreamReader( new java.io.ByteArrayInputStream( ( byte[] )resultList.get( 0 ).get(
                        "stream" ) ) ) );

        String readLine = null;
        StringBuffer response = new StringBuffer();

        do
        {
            readLine = reader.readLine();

            if ( readLine != null )
            {
                response = response.append( readLine );
            }
        }
        while ( readLine != null );

        return "<temp>" + response.toString() + "</temp>";

    }
}
