// Package 
package gov.va.med.esr.common.batchprocess;

// Java Classes
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.dialect.Dialect;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;

import gov.va.med.fw.scheduling.AbstractScheduledProcess;
import gov.va.med.fw.scheduling.ScheduledProcessInvocationContext;

/**
 * A batch process that resets the com mailing barcode sequence.
 *
 * @author Andrew Pach
 * @version 3.0
 */
public class ResetComMailingBarcodeSequenceProcess extends AbstractScheduledProcess implements InitializingBean
{
    private String sequenceName = null;
    private Properties hibernateProperties = null;
    private DataSource dataSource = null;
    private String[] updateSequenceSql = null;

    /**
     * Executes this batch process.
     *
     * @param args process arguments
     *
     * @throws Exception if any problems were encountered.
     */
    protected void executeProcess(ScheduledProcessInvocationContext context) throws Exception
    {
        // Create a JDBC Template to execute our statements
        JdbcTemplate template = new JdbcTemplate(dataSource);

        // Perform the batch update to drop and recreate the sequence
        template.batchUpdate(updateSequenceSql);
    }

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */
    public void afterPropertiesSet()
    {
        // Call parent implementation first
        super.afterPropertiesSet();

        // Get the drop and create sequence SQL strings
        Dialect dialect = Dialect.getDialect(hibernateProperties);
        String[] dropSequenceSql = dialect.getDropSequenceStrings(sequenceName);
        String[] createSequenceSql = dialect.getCreateSequenceStrings(sequenceName);

        // Create a list of SQL statements to drop and then recreate the sequence in a batch update
        updateSequenceSql = new String[dropSequenceSql.length + createSequenceSql.length];
        int index = 0;
        for (int i=0; i < dropSequenceSql.length; i++)
        {
            updateSequenceSql[index] = dropSequenceSql[i];
            index++;
        }
        for (int i=0; i < createSequenceSql.length; i++)
        {
            updateSequenceSql[index] = createSequenceSql[i];
            index++;
        }
    }

    public String getSequenceName()
    {
        return sequenceName;
    }

    public void setSequenceName(String sequenceName)
    {
        this.sequenceName = sequenceName;
    }

    public Properties getHibernateProperties()
    {
        return hibernateProperties;
    }

    public void setHibernateProperties(Properties hibernateProperties)
    {
        this.hibernateProperties = hibernateProperties;
    }

    public DataSource getDataSource()
    {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource)
    {
        this.dataSource = dataSource;
    }
}
