package gov.va.med.fw.scheduling;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.quartz.impl.jdbcjobstore.oracle.weblogic.WebLogicOracleDelegate;

public class CustomJDBCDelegate extends WebLogicOracleDelegate {

	public CustomJDBCDelegate(Log logger, String tablePrefix, String instanceId) {
		super(logger, tablePrefix, instanceId);
	}

	/**
	 * override updateTriggerStateFromOtherStatesBeforeTime from StdJDBCDelegate.java so that we will not 
	 * misfire SIMPLE triggers like SSN and PH Clocks. If the execution of these clocks are delayed for some
	 * reason , they should not be misfired.
	 */
	public int updateTriggerStateFromOtherStatesBeforeTime(Connection conn,
			String newState, String oldState1, String oldState2, long time)
			throws SQLException {
			if ("MISFIRED".equals(newState) && "WAITING".equals(oldState1) && "WAITING".equals(oldState2) )
			{
				return updateTriggerStateFromOtherStatesToMisFiredBeforeTime(conn, newState, oldState1, oldState2, time);
			}
			else
			{
				return super.updateTriggerStateFromOtherStatesBeforeTime(conn, newState, oldState1, oldState2, time);
			}
	}

	
	
	private int updateTriggerStateFromOtherStatesToMisFiredBeforeTime(Connection conn,String newState, String oldState1, String oldState2,
			long time)
			throws SQLException {
		PreparedStatement ps = null;
		int i;
		try {
			ps = conn
					.prepareStatement(rtp("UPDATE {0}TRIGGERS SET TRIGGER_STATE = ? WHERE (TRIGGER_STATE = ? OR TRIGGER_STATE = ?) AND TRIGGER_TYPE NOT LIKE ? AND NEXT_FIRE_TIME < ?"));
			ps.setString(1, newState);
			ps.setString(2, oldState1);
			ps.setString(3, oldState2);
			ps.setString(4, "SIMPLE");
			ps.setLong(5, time);
			i = ps.executeUpdate();
		} finally {
			if (null != ps)
				try {
					ps.close();
				} catch (SQLException ignore) {
				}
		}
		return i;
	}
}
