

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


import gov.va.med.cds.exception.ErrorCodeEnum;
import gov.va.med.cds.template.TemplateManager;

import java.io.StringReader;

import javax.annotation.Resource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Validator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;


public class NonSequenceResponseSchemaSequencer
    implements
        ResponseSequencerInterface
{
    @Resource
    private TemplateManager templateManager;


    @Override
    public Document sequence( String templateId, String sourceXml, boolean validateReadResponse )
    {
        if ( sourceXml == null || sourceXml.isEmpty() )
        {
            throw new SequencerException( ErrorCodeEnum.SCHEMA_VALIDATION_FAILED, "Source document is null" );
        }

        Document sourceDoc = null;
        try
        {
            sourceDoc = DocumentHelper.parseText( sourceXml );
        }
        catch ( DocumentException dex )
        {
            throw new SequencerException( ErrorCodeEnum.SCHEMA_VALIDATION_FAILED, dex, dex.getMessage() );
        }

        return sequence( templateId, sourceDoc, validateReadResponse );
    }


    @Override
    public Document sequence( String templateId, Document sourceDoc, boolean validateReadResponse )
    {
        if ( templateId == null || templateId.isEmpty() )
        {
            throw new SequencerException( ErrorCodeEnum.READ_REQUEST_TEMPLATE_ID_NULL );
        }

        if ( sourceDoc == null || !sourceDoc.hasContent() )
        {
            throw new SequencerException( ErrorCodeEnum.SCHEMA_XML_NULL );
        }

        Validator validator = null;
        if ( validateReadResponse )
        {
            try
            {
                validator = templateManager.getTemplateValidator( templateId );
                validator.validate( new StreamSource( new StringReader( sourceDoc.asXML() ) ) );
            }
            catch ( Exception e )
            {
                throw new SequencerException( ErrorCodeEnum.SCHEMA_VALIDATION_FAILED, e, e.getMessage() );
            }
        }

        return sourceDoc;

    }


    public void setTemplateManager( TemplateManager templateManager )
    {
        this.templateManager = templateManager;
    }

}
