package com.mason.server.dao.jdo;

import java.util.Collection;
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.IProjectDAO;
import com.mason.server.model.Project;

public class ProjectDAO implements IProjectDAO {

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

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

	public Project getBySlug(String slug, long ownerId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Project.class,
				"slug == :slug && ownerId == :ownerId");
		q.setUnique(true);
		Project result = null;
		try {
			result = (Project) q.execute(slug, ownerId);
			result = pm.detachCopy(result);
		} finally {
			pm.close();
		}
		return result;
	}

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

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

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

	@SuppressWarnings("unchecked")
	@Override
	public List<Project> getAll() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Project.class);
		q.setOrdering("description asc");
		Collection<Project> results = null;
		try {
			results = pm.detachCopyAll((Collection<Project>) q.execute());
		} finally {
			q.closeAll();
			pm.close();
		}
		return (List<Project>) results;
	}

	@SuppressWarnings("unchecked")
	public List<Project> getAllByUserId(long ownerId) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query q = pm.newQuery(Project.class, "ownerId == :ownerId");
		q.setOrdering("description asc");
		Collection<Project> results = null;
		try {
			results = pm
					.detachCopyAll((Collection<Project>) q.execute(ownerId));
		} finally {
			q.closeAll();
			pm.close();
		}
		return (List<Project>) results;
	}

}
