package org.jerrymouse.database.jdo;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

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

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

	@Override
	public void delete(Object object) {
		log.info("deleting " + object);

		PersistenceManager pm = JDOPMF.getPersistenceManager();
		Transaction transaction = pm.currentTransaction();
		try {
			transaction.begin();
			pm.deletePersistent(object);
			transaction.commit();
			log.info("delete success");

		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			pm.close();
		}
	}

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

		Object object;
		PersistenceManager pm = JDOPMF.getPersistenceManager();
		try {
			object = pm.getObjectById(type, key);
			log.info("getting success");

		} finally {
			pm.close();
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	public List<T> list(Class<T> type) {
		log.info("getList " + type.getName());

		List objects;
		PersistenceManager pm = JDOPMF.getPersistenceManager();
		try {
			Query query = pm.newQuery(type);
			objects = (List) query.execute();
			objects.size();
			log.info("getList success");

		} finally {
			pm.close();
		}
		return objects;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list(Class<T> type, List keys) {
		log.info("getList " + type.getName());

		List list = new ArrayList();
		PersistenceManager pm = JDOPMF.getPersistenceManager();
		try {
			for (Object key : keys) {
				list.add(pm.getObjectById(type, key));
			}
			log.info("getList success");

		} finally {
			pm.close();
		}
		return list;
	}

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

	public void put(T object) {
		log.info("putting " + object);
		PersistenceManager pm = JDOPMF.getPersistenceManager();
		Transaction transaction = pm.currentTransaction();
		try {
			transaction.begin();
			pm.makePersistent(object);
			transaction.commit();
			log.info("put success");
		} finally {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			pm.close();
		}
	}
}
