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

package ejb;

import java.util.List;
import java.util.Vector;
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 NewsFacade {
    @PersistenceContext(unitName = "NewsApp-ejbPU")
    private EntityManager em;

    public void create(News news) {
        em.persist(news);
    }

    public void edit(News news) {
        em.merge(news);
    }

    public void remove(News news) {
        em.remove(em.merge(news));
    }

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

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

    public List<News> findRange(int[] range) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(News.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<News> rt = cq.from(News.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }

    public Vector<Long> getByKeyword(String[] keyword)
    {
        int size=keyword.length;
        Vector<Long> resultList=new Vector<Long>();

        for(int i=0;i<size;i++)
        {
            List<Long> temp= em.createNativeQuery("SELECT ID FROM NEWS WHERE KEYWORDS LIKE '%"+keyword[i]+"%'").getResultList();
            int sizetemp=temp.size();
            for(int j=0;j<sizetemp;j++)
            {
                if(!resultList.contains(Long.parseLong(temp.get(j).toString())))
                    resultList.addElement(Long.parseLong(temp.get(j).toString()));
            }
        }

        return resultList;
        
    }

}
