package gov.va.med.esr.messaging.service.inbound;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import gov.va.med.esr.messaging.util.AbstractMessagingTest;
import gov.va.med.fw.hl7.BatchMessage;
/**
 * 
 * @author Rajiv Patnaik
 * Created on Oct 10, 2006
 * @version 1.0
 * 
 * Copyright © 2006 VHA. All rights reserved
 */
public abstract class AbstractCreateHL7MessageFileTest extends AbstractMessagingTest
{

	protected abstract  String getOutputFileName();	
    
	/**
	 * An instance of hibernateTemplate
	 */
	private HibernateTemplate hibernateTemplate = null;    
	
	/**
	 * @return Returns the hibernateTemplate.
	 */
	protected HibernateTemplate getHibernateTemplate() {
		if( this.hibernateTemplate == null ) {
			this.hibernateTemplate = (HibernateTemplate)this.applicationContext.getBean( "hibernateTemplate" );
		}
		return this.hibernateTemplate;
	} 	
	
	protected void createTestFile(BatchMessage message, String outputFileName) {
		BufferedWriter out = null;
		try {
			OutputStreamWriter output = new OutputStreamWriter(
					new BufferedOutputStream(new FileOutputStream(outputFileName)));
			out = new BufferedWriter(output);
			out.write(message.getMessageData());
			
		} catch (Exception e) {
		    e.printStackTrace();
		}finally
		{
		    try
            {
                if (out != null) {
                	out.flush();                
                	out.close();
                }
            } catch (IOException e1)
            {
                e1.printStackTrace();
            }
		    
		}
	}
	
    protected List getQueryResults(final String queryStr)
    {
        return (List) getHibernateTemplate().execute(new HibernateCallback() {
            public Object doInHibernate(Session session)
                    throws HibernateException
            {
                Query query = session.createSQLQuery(queryStr);
                return query.list();
            }
        });

    }	
	
}
