package com.mason.server.dao.jdo;

import java.util.List;

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

import com.mason.server.dao.jdo.PMF;
import com.mason.server.dao.generics.GenericDAO;
import com.mason.server.model.Log;

public class LogDAO implements GenericDAO<Log> {

	@Override
	public Log add(Log object) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			object = pm.makePersistent(object);
			object = pm.detachCopy(object);
		} finally {
			pm.close();
		}
		return object;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Log> getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Log.class);
		q.setOrdering("date descending ");
		List<Log> results = null;
		try {
			results = (List<Log>) q.execute();
			if (results.isEmpty()) {
				results = null;
			}
		} finally {
			q.closeAll();
			pm.close();
		}
		return results;
	}

	@Override
	public Log get(long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Log.class, "id == :id");
		q.setUnique(true);
		Log result = null;
		try {
			result = (Log) q.execute(id);
			result = pm.detachCopy(result);
		} finally {
			pm.close();
		}
		return result;
	}

	@Override
	public boolean delete(Log object) {
		return deleteById(object.getId());
	}

	@Override
	public boolean deleteById(long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.deletePersistent(get(id));
		} catch (Exception e) {
			return false;
		} finally {
			pm.close();
		}
		return true;
	}

	@Override
	public Log update(Log object) {
		return null;
	}

	public boolean clear() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Log.class);
		try {
			q.deletePersistentAll();
		} finally {
			q.closeAll();
			pm.close();
		}
		return true;
	}

}
