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

package gov.va.med.fw.service.transaction;

import java.sql.Timestamp;

import org.apache.commons.lang.Validate;
import org.springframework.transaction.support.TransactionSynchronization;

import gov.va.med.fw.cache.TransactionTimestampCacheManager;
import gov.va.med.fw.service.AbstractComponent;

/**
 * TransactionSynchronization implementation to perform management of the global
 * transaction timestamp during nested calls. This is to ensure each nested
 * Transaction has its own global timestamp.
 * 
 * NOTE: This implementation is stateful in cases of suspend/resume.
 * 
 * Created Nov 2, 2005 1:57:49 PM
 * 
 * @author DNS   BOHMEG
 */
public class TransactionSynchronizationForTimestamp extends AbstractComponent implements
		TransactionSynchronization {

	public void flush() {
	}

	private TransactionTimestampCacheManager cacheManager;
	private Timestamp ts;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.transaction.support.TransactionSynchronization#suspend
	 * ()
	 */
	public void suspend() {
		if (cacheManager.hasTimestamp()) {
			ts = cacheManager.removeTimestamp();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.transaction.support.TransactionSynchronization#resume
	 * ()
	 */
	public void resume() {
		if (ts != null) {
			cacheManager.storeTransactionTimestamp(ts);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.transaction.support.TransactionSynchronization#
	 * beforeCommit(boolean)
	 */
	public void beforeCommit(boolean readOnly) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.transaction.support.TransactionSynchronization#
	 * beforeCompletion()
	 */
	public void beforeCompletion() {
		// TODO Auto-generated method stub

	}

	/**
	 * @see org.springframework.transaction.support.TransactionSynchronization#afterCommit()
	 */
	public void afterCommit() {
		// TODO Auto-generated method stub
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.springframework.transaction.support.TransactionSynchronization#
	 * afterCompletion(int)
	 */
	public void afterCompletion(int status) {
		cacheManager.removeTimestamp();
	}

	public void afterPropertiesSet() throws Exception {
		super.afterPropertiesSet();
		Validate.notNull(cacheManager);
	}

	/**
	 * @return Returns the cacheManager.
	 */
	public TransactionTimestampCacheManager getCacheManager() {
		return cacheManager;
	}

	/**
	 * @param cacheManager
	 *            The cacheManager to set.
	 */
	public void setCacheManager(TransactionTimestampCacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}
}