

package gov.va.med.cds.mediator.work;


import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.mediator.MessageProcessorInterface;

import java.util.List;

import org.springframework.util.StringUtils;


public class RequestResponseWorkFlow
    implements
        WorkFlowInterface,
        MessageProcessorInterface
{
    private String wsnPersistOriginal;

    private String wsnInputMessage;

    private String wsnOutputMessage;

    private List<WorkerInterface> work;


    public void doWork( WorkStateInterface workState )
    {
        for ( WorkerInterface w : work )
        {
            try
            {
                w.doWork( workState );
            }
            catch ( Exception e )
            {
                workState.addException( e );
            }
        }
    }


    public String processMessage( String source, boolean persistOriginal )
    {
        WorkStateInterface workState = new MapBackedWorkState();
        String response = null;
        try
        {
            workState.registerWorkState( wsnInputMessage, source );
            workState.registerWorkState( wsnPersistOriginal, persistOriginal );

            doWork( workState );
            response = ( String )workState.locateWorkState( wsnOutputMessage );

            if ( !StringUtils.startsWithIgnoreCase( response, "<?xml version=" ) )
            {
                throw new WorkStateException( ErrorCodeEnum.WORK_STATE_EXPECTED_DATA_NOT_PRESENT_EXCEPTION, response );
            }

            return response;
        }
        catch ( Exception e )
        {
            workState.addException( e );
            StringBuffer errorMessage = new StringBuffer(
                            "<?xml version=\"1.0\" encoding=\"UTF-8\"?><clinicaldata:ClinicalData xmlns:clinicaldata=\"Clinicaldata\"><errorSection><fatalErrors><errorCode>CATASTROPHIC ERROR - Unable to process message.  Following is a list of one or more exceptions encountered:</errorCode><displayMessage>" );
            for ( Exception exception : workState.getExceptions() )
            {
                errorMessage.append( "\n" + exception.getMessage() + exception.getCause() );
            }

            errorMessage.append( "</displayMessage></fatalErrors></errorSection></clinicaldata:ClinicalData>" );
            return errorMessage.toString();
        }

    }


    public void setWork( List<WorkerInterface> work )
    {
        this.work = work;
    }


    public void setWsnInputMessage( String wsnInputMessage )
    {
        this.wsnInputMessage = wsnInputMessage;
    }


    public void setWsnOutputMessage( String wsnOutputMessage )
    {
        this.wsnOutputMessage = wsnOutputMessage;
    }


    public void setWsnPersistOriginal( String wsnPersistOriginal )
    {
        this.wsnPersistOriginal = wsnPersistOriginal;
    }

}
