package com.fp.persistence.commondb;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

public class FlipUserTransaction implements UserTransaction {

	private EntityManager em;

	public FlipUserTransaction(EntityManager em) {
		this.em = em;
	}

	public void begin() throws NotSupportedException {
		if (em.getTransaction().isActive()) {
			throw new NotSupportedException();
		}
		em.getTransaction().begin();
	}

	public void commit() throws RollbackException {
		try {
			em.getTransaction().commit();
		} catch (javax.persistence.RollbackException e) {
			throw new RollbackException(e.getMessage());
		}
	}

	public void rollback() throws SystemException {
		try {
			em.getTransaction().rollback();
		} catch (PersistenceException e) {
			throw new SystemException(e.getMessage());
		}
	}

	public void setRollbackOnly() {
		em.getTransaction().setRollbackOnly();
	}

	public int getStatus() {
		if (em.getTransaction().isActive()) {
			return Status.STATUS_ACTIVE;
		} else {
			return Status.STATUS_NO_TRANSACTION;
		}
	}

	public void setTransactionTimeout(int timeout) {
		throw new UnsupportedOperationException();
	}

	public void close() {
		try {
			if (em.isOpen()) {
	        	em.clear();
	            em.close();
	        }	
		} catch (Exception e) {
			// No hacer nada la sessioo no est aabierta
		}
	} 
}
