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.IUmlElementDAO;
import com.mason.server.model.UmlElement;

public class UmlElementDAO implements IUmlElementDAO {

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

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

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

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

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

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

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

}
