package com.ibtp.kontor.library.dal;

import com.ibtp.kontor.dal.BaseImpl;
import com.ibtp.kontor.library.entity.ArticleEntity;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * Created by tpeetz on 23.01.2015.
 */
public class ArticleImpl extends BaseImpl implements ArticleDao {

    @Override
    public ArticleEntity getById(Long id) {
        Query query = getEntityManager().createNamedQuery("Article.findById");
        query.setParameter("id", id);
        return (ArticleEntity)query.getSingleResult();
    }

    @Override
    public List<ArticleEntity> findByIds(List<Long> ids) {
        return null;
    }

    @Override
    public List<ArticleEntity> findAll() {
        Query query = getEntityManager().createNamedQuery("Article.findAll");
        //noinspection unchecked
        return query.getResultList();
    }

    @Override
    public List<ArticleEntity> findByTitle(String title) {
        Query query = getEntityManager().createNamedQuery("Article.findByTitle");
        query.setParameter("title", title);
        //noinspection unchecked
        return query.getResultList();
    }

    public ArticleEntity addArticle(String title) {
        ArticleEntity entity = new ArticleEntity(title);
        store(entity);
        return entity;
    }

    @Override
    public ArticleEntity store(ArticleEntity entity) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
        return entity;
    }

    @Override
    public void delete(ArticleEntity entity) {
        EntityManager em = getEntityManager();
        em.getTransaction().begin();
        em.remove(entity);
        em.getTransaction().commit();
    }
}
