package com.ibtp.kontor.comics.dal;

import com.ibtp.kontor.comics.entity.ComicEntity;
import com.ibtp.kontor.dal.BaseImpl;

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

/**
 * Created by TPEETZ on 28.01.2015.
 */
public class ComicImpl extends BaseImpl implements ComicDao {

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

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

    @Override
    public Collection<ComicEntity> findByTitle(String title) {
        Query query = getEntityManager().createNamedQuery("Comic.findByTitle");
        query.setParameter("title", title);
        return query.getResultList();
    }

    @Override
    public Collection<ComicEntity> findAll() {
        Query query = getEntityManager().createNamedQuery("Comic.findAll");
        return query.getResultList();
    }

    @Override
    public ComicEntity addComic(String title) {
        ComicEntity comicEntity = new ComicEntity();
        comicEntity.setTitle(title);
        store(comicEntity);
        return comicEntity;
    }

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

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