package org.jerrymouse.database.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jerrymouse.database.DaoSupport;

public class JPADaoSupport<T> implements DaoSupport<T> {
	private static final Log log = LogFactory.getLog(JPADaoSupport.class);

	@Override
	public void delete(Object object) {
		log.info("putting " + object);
		EntityManager em = JPAPMF.getEntityManager();
		EntityTransaction transaction = em.getTransaction();
		try {
			transaction.begin();
			em.remove(object);
			transaction.commit();
			log.info("put success");
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			em.close();
		}
	}

	@Override
	public Object get(Object key, Class type) {
		log.info("getting " + key.toString());

		Object object;
		EntityManager pm = JPAPMF.getEntityManager();
		try {
			object = pm.find(type, key);
			log.info("getting success");
		} finally {
			pm.close();
		}
		return object;
	}

	@Override
	public List<T> list(Class<T> type) {
		EntityManager pm = JPAPMF.getEntityManager();
		Query query = pm.createQuery("SELECT e FROM "+type.getName()+" e");
		List<T> list = query.getResultList();
		list.size();
		pm.close();
		return list;
	}

	@Override
	public List list(Class type, List keys) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void post(Object object) {
		throw new UnsupportedOperationException();
	}

	@Override
	public void put(T object) {
		log.info("putting " + object);
		EntityManager em = JPAPMF.getEntityManager();
		EntityTransaction transaction = em.getTransaction();
		try {
			transaction.begin();
			em.persist(object);
			transaction.commit();
			log.info("put success");
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			em.close();
		}
	}

}
