package com.mason.server.dao.jdo;

import java.util.ArrayList;
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.IUserDAO;
import com.mason.server.model.DbUser;

public class UserDAO implements IUserDAO {

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

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

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

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

	@Override
	public boolean delete(DbUser 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;
	}

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

	@Override
	public List<String> getAllUsernames() {
		List<String> results = new ArrayList<String>();
		List<DbUser> users = getAll();
		
		for (DbUser u : users) {
			results.add(u.getUsername());
		}
		
		return results;
	}

}