/********************************************************************
 * Copyright © 2005 VHA. All rights reserved
 ********************************************************************/

package gov.va.med.fw.persistent.hibernate;

import java.util.List;

import org.apache.commons.lang.Validate;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.springframework.beans.factory.InitializingBean;

/**
 * Initial javadoc for class CurrentTimestampAction. TODO - Add content here
 * 
 * Created Aug 8, 2005 5:59:59 PM
 * 
 * @author DNS   bohmeg
 */
public class CurrentTimestampAction extends AbstractDAOAction implements
		InitializingBean {
	private final String CURRENT_TIMESTAMP = "ts";
	
	private String dialectSpecificCurrentTimestampFunction;

	private String dialectSpecificTable;

	private String sqlQuery;

	public CurrentTimestampAction() {
	}

	/**
	 * @return Returns the dialectSpecificCurrentTimestampFunction.
	 */
	public String getDialectSpecificCurrentTimestampFunction() {
		return dialectSpecificCurrentTimestampFunction;
	}

	/**
	 * @param dialectSpecificCurrentTimestampFunction
	 *            The dialectSpecificCurrentTimestampFunction to set.
	 */
	public void setDialectSpecificCurrentTimestampFunction(
			String dialectSpecificCurrentTimestampFunction) {
		this.dialectSpecificCurrentTimestampFunction = dialectSpecificCurrentTimestampFunction;
	}

	/**
	 * @return Returns the dialectSpecificTable.
	 */
	public String getDialectSpecificTable() {
		return dialectSpecificTable;
	}

	/**
	 * @param dialectSpecificTable
	 *            The dialectSpecificTable to set.
	 */
	public void setDialectSpecificTable(String dialectSpecificTable) {
		this.dialectSpecificTable = dialectSpecificTable;
	}

	protected Object execute(Session session) {
		// let's not cause unnecessary flushing because of this query
		FlushMode sessionFlushMode = session.getFlushMode();
		session.setFlushMode(FlushMode.NEVER);
		List results = session.createSQLQuery(sqlQuery).addScalar(
				CURRENT_TIMESTAMP, Hibernate.TIMESTAMP).list();
		session.setFlushMode(sessionFlushMode);
		return results;
	}

	public void afterPropertiesSet() {
		Validate.notNull(dialectSpecificCurrentTimestampFunction);
		Validate.notNull(dialectSpecificTable);

		// initialize query
		sqlQuery = "select " + dialectSpecificCurrentTimestampFunction + " as "
				+ CURRENT_TIMESTAMP + " from " + dialectSpecificTable;
	}
}
