

package gov.va.med.cds.tools.cleanup.errorq;


import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gov.va.med.cds.junit.runners.Suite;
import gov.va.med.cds.junit.runners.SuiteAwareSpringRunner;
import gov.va.med.cds.testharness.AbstractBaseTest;
import gov.va.med.cds.util.StreamUtil;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;


@RunWith( SuiteAwareSpringRunner.class )
@ContextConfiguration( locations = { "classpath:gov/va/med/cds/tools/cleanup/errorq/errorQCleanUpContext.xml" } )
public class ProcessClinicalMessageCommandTest
    extends
        AbstractBaseTest
{
    //injected by Spring
    private MessageCommandInterface processClinicalMessageCommand;
    private JdbcTemplate hdrJdbcTemplate;

    private ResourceLoader resourceLoader = new DefaultResourceLoader();


    @Test
    public void testProcessClinicalMessageCommandNotNull( )
    {
        assertNotNull( processClinicalMessageCommand );
    }


    @Test
    @Suite( groups = { "checkintest" } )
    public void testExecute( )
        throws Exception
    {
        Resource resource = resourceLoader.getResource( "classpath:gov/va/med/cds/tools/cleanup/errorq/hdrvtls.er7" );
        String hl7Message = StreamUtil.resourceToString( resource );

        String returnValue = processClinicalMessageCommand.execute( hl7Message, true );

        assertTrue( returnValue.contains( "<errorSection/>" ) );

        String requestId = returnValue
                        .substring( returnValue.indexOf( "<requestId>" ) + "<requestId>".length(), returnValue.indexOf( "</requestId>" ) );

        cleanDb( requestId );
    }


    private void cleanDb( String requestId )
    {
        int noRows = hdrJdbcTemplate.update( "DELETE FROM VITAL_V WHERE REQUEST_ID = ?", new Object[] { requestId } );
        assertTrue( 1 == noRows );
    }


    @javax.annotation.Resource
    public void setProcessClinicalMessageCommand( MessageCommandInterface processClinicalMessageCommand )
    {
        this.processClinicalMessageCommand = processClinicalMessageCommand;
    }


    @javax.annotation.Resource
    public void setHdrJdbcTemplate( JdbcTemplate hdrJdbcTemplate )
    {
        this.hdrJdbcTemplate = hdrJdbcTemplate;
    }
}
