package inc.monsters.mias.data.facade;

import inc.monsters.mias.data.Kid;

import java.util.List;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class KidService
 */
@Stateless
public class KidServiceBean implements KidService {
	private static final Logger log = Logger.getLogger("inc.monsters.mias");
	
	@PersistenceContext(unitName="MIAS-EJB")
	private EntityManager em;

    /**
     * Default constructor. 
     */
    public KidServiceBean() {
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<Kid> getKids() {
    	Query q = em.createNamedQuery("Kid.all");
    	return q.getResultList();
	}

	@Override
	public boolean existsKid(Kid k) {
		if(null == em.find(Kid.class, k.getId())) {
			return false;
		} else {
			return true;
		}
	}
	
	@Override
	public void updateKid(Kid k) {
		log.fine("Merging kid with ID " + k.getId() + "...");
		if(null == em.find(Kid.class, k.getId())) {
			throw new IllegalArgumentException("Unknown kid id: " + k.getId());
		}
		
   		em.merge(k);
    }

	@Override
	public void addKid(Kid k) {
		log.fine("Adding new kid:" + k);
   		em.persist(k);
	}
	
	@Override
	public void deleteKid(Kid k) {
		// We cannot call remove with k, because this is a detached object.
    	// Instead we call find() to get the managed object with the same ID.
    	Kid d = em.find(Kid.class, k.getId());
    	if (d != null) {
    		em.remove(d);
    	} else {
    		throw new IllegalArgumentException("Unknown kid id: " + k.getId());
    	}
	}
}