/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ejb;

import java.sql.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author zwergnase
 */
@Stateless
public class SeferFacade {
    @PersistenceContext(unitName = "NewsApp-ejbPU")
    private EntityManager em;

    public void create(Sefer sefer) {
        em.persist(sefer);
    }

    public void edit(Sefer sefer) {
        em.merge(sefer);
    }

    public void remove(Sefer sefer) {
        em.remove(em.merge(sefer));
    }

    public Sefer find(Object id) {
        return em.find(Sefer.class, id);
    }

    public List<Sefer> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Sefer.class));
        return em.createQuery(cq).getResultList();
    }

    public List<Sefer> findRange(int[] range) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Sefer.class));
        Query q = em.createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }


    public List<Long> findSefersFromLocation(Long LineId, Date D)
    {
         List<Long> resultList = em.createNativeQuery("SELECT ID FROM SEFER WHERE LINEID="+LineId+
                 " AND NOT EXISTS(SELECT * FROM SCHEDULE WHERE SEFER.ID=SEFERID AND SCHEDULEDATE='"+D+"')").getResultList();
         if(resultList.size()==0)
             return null;
         return resultList;
    }


    public int count() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<Sefer> rt = cq.from(Sefer.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

}
