/*
 * 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 e1502608
 */
@Stateless
public class ScheduleFacade {
    @PersistenceContext(unitName = "NewsApp-ejbPU")
    private EntityManager em;

    public void create(Schedule schedule) {
        em.persist(schedule);
    }

    public void edit(Schedule schedule) {
        em.merge(schedule);
    }

    public void remove(Schedule schedule) {
        em.remove(em.merge(schedule));
    }

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

    public List<Long> scheduleForMach(long MachId)
    {
        List<Long> resultList = em.createNativeQuery("SELECT ID FROM SCHEDULE WHERE MACHINSTID = "+ MachId).getResultList();
        if(resultList.size()==0)
            return null;
        return resultList;
    }

    public List<Long> scheduleForMach2(Long MachId,Date date)
    {
        List<Long> resultList = em.createNativeQuery("SELECT ID FROM SCHEDULE WHERE MACHINSTID = "+ MachId+
                " AND SCHEDULEDATE='"+date+"'").getResultList();
        if(resultList.size()==0)
            return null;
        return resultList;
    }



    // aynı zamanda tarihli çağrılabilsin
    //makinist yarını da görebilir mesela..
    // bir de silme fonksiyonu tanımla tarihte / aşağıda olanları silsin
// bir yerden br yere seferler listeleme
    // clean by date yapılabilir olsun!!
    


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

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

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

}
