

package gov.va.med.cds.socket.server;


import gov.va.med.cds.testharness.AbstractBaseTest;
import gov.va.med.cds.util.MllpUtil;
import gov.va.med.cds.util.StreamUtil;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.junit.Test;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;


public class ApplicationAcknowledgementTest
    extends
        AbstractBaseTest
{

    private static ResourceLoader loader = new DefaultResourceLoader();


    //@Test
    public void testSendAppAck( )
        throws InterruptedException, IOException
    {
        MinaClientHandlerDataTest minaClientHandlerDataTest;

        minaClientHandlerDataTest = new MinaClientHandlerDataTest();
        minaClientHandlerDataTest.setValues( getHl7er7() );
        connectToServer( minaClientHandlerDataTest );
    }


    private IoBuffer getHl7er7( )
    {

        String hl7Er7Message = null;

        Resource resource = loader.getResource( "classpath:gov/va/med/cds/socket/server/applicationAck.er7" );

        try
        {
            hl7Er7Message = StreamUtil.streamToString( resource.getInputStream() );
        }
        catch ( IOException e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ByteBuffer buffer = encodeToMllp( hl7Er7Message );

        IoBuffer messageIoBuffer = IoBuffer.allocate( buffer.limit() );

        int index = 0;

        while ( buffer.hasRemaining() && ( index < buffer.limit() ) )
        {
            messageIoBuffer.put( index, buffer.get( index ) );

            index++ ;
        }

        return messageIoBuffer;

    }


    private ByteBuffer encodeToMllp( String hl7Er7Message )
    {
        ByteBuffer buffer = ByteBuffer.allocate( hl7Er7Message.toString().getBytes().length );

        buffer.put( hl7Er7Message.toString().getBytes() );

        return MllpUtil.encode( buffer, Charset.forName( "ISO-8859-1" ), Charset.defaultCharset() );
    }


    private void connectToServer( MinaClientHandlerDataTest minaClientHandlerDataTest )
        throws InterruptedException,
            IOException
    {
        IoConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast( "logger", new LoggingFilter() );
        connector.setHandler( minaClientHandlerDataTest );
        connector.connect( new InetSocketAddress( Integer.parseInt( "5001" ) ) );
        connector.setConnectTimeoutMillis( 5000 );
    }

}
