package ejb.visit;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import TO.VisitTO;
import common.QuestionStatus;
import ejb.common.CommonFacadeLocal;
import jpa.QuestionJPA;
import jpa.VisitJPA;

/**
 * EJB Session Bean Class para la Practica 2, Ejercicio 1 (ISCSD) Implementa los métodos de la capa de negocio que implementan la logica de negocio y la interacción con la capa de
 * persistencia.
 * 
 * @author mark
 *
 */
@Stateless
public class VisitFacadeBean implements VisitFacadeRemote {
	// Persistence Unit Context
	@PersistenceContext(unitName = "MyHealth")
	EntityManager entman;

	@EJB
	CommonFacadeLocal commonServices;

	public Long getScheduledVisitsCount(int familyDoctorId, Date date) {
		TypedQuery<Long> query = entman.createQuery("SELECT count(1) from VisitJPA v where v.date=:date and v.familyDoctor.id=:docId", Long.class);
		query.setParameter("date", date);
		query.setParameter("docId", familyDoctorId);

		return query.getSingleResult();
	}
	
	public List<VisitTO> listAllScheduledVisitsPaged(int familyDoctorId, Date date, int pageNumber, int pageSize) {
		TypedQuery<VisitJPA> query = entman.createQuery("SELECT v from VisitJPA v where v.date=:date and v.familyDoctor.id=:docId order by v.date, v.time", VisitJPA.class);
		query.setParameter("date", date);
		query.setParameter("docId", familyDoctorId);

		if (pageSize > 0) {
			query.setFirstResult(pageNumber * pageSize);
			query.setMaxResults(pageSize);
		}

		List<VisitJPA> allJPA = query.getResultList();
		List<VisitTO> listTO = new ArrayList<VisitTO>();

		for (VisitJPA item : allJPA) {
			listTO.add(commonServices.getPOJOforVisitJPA(item, 1));
		}

		return listTO;
	}

}
