

package gov.va.med.cds.ars.model;


import gov.va.med.cds.ars.jaxb.JaxbHelper;
import gov.va.med.cds.ars.requestresponse.generated.HTReportType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class ModelMarshaller 
    implements ModelMarshallerInterface
{
    protected static final String ARS_REPORT_SCHEMA_LOCATION = "classpath:resources/HTResponse.xsd";

    private Log logger = LogFactory.getLog( ModelMarshaller.class );
    private JaxbHelper jaxbHelper = null;

    
    public ModelMarshaller() 
    {
    }

    
    @Override
    public String marshalToXml( HTReportType reportResults ) 
    {
        String result = null;
        
        try
        {
            result = jaxbHelper.marshal( reportResults, ARS_REPORT_SCHEMA_LOCATION );
        } 
        catch( Exception e ) 
        {
            String error = "marshalToXml Caught Exception: " + e.getMessage();
            result = "Marshaller Failure: " + error;
            e.printStackTrace();
            if ( logger.isDebugEnabled() )
            {
                logger.debug(error);
            }
        }
        
        return convertString (result);
    }   
    
    
    public void setJaxbHelper( JaxbHelper aJaxbHelper )
    {
        this.jaxbHelper = aJaxbHelper;
    }
    
    private String convertString ( String inputString )
    {
    	StringBuffer  sb  = new StringBuffer(inputString);
    	int index=0;
    	while (index > -1)
    	{
    		index = sb.indexOf("&lt;");
    		if (index  != -1)
    		{
    			sb.replace(index, index+4, "<");
    		}
    	}
    	index=0;
    	while (index > -1)
    	{
    		index = sb.indexOf("&gt;");
    		if (index  != -1)
    		{
    			sb.replace(index, index+4, ">");
    		}
    	}

    	return sb.toString();
    }
}
