package com.ibtp.kontor.library.dal;

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

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

/**
 * Created by thomas on 23.01.15.
 */
public class AuthorImpl extends BaseImpl implements AuthorDao {

    public AuthorImpl() {}

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

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

    @Override
    public List<AuthorEntity> findByName(String name) {
        Query query = getEntityManager().createNamedQuery("Author.findByName");
        query.setParameter("name", name);
        return query.getResultList();
    }

    @Override
    public List<AuthorEntity> findAll() {
        Query query = getEntityManager().createNamedQuery("Author.findAll");
        return query.getResultList();
    }

    @Override
    public AuthorEntity addAuthor(String name) {
        AuthorEntity author = new AuthorEntity(name);
        store(author);
        return author;
    }

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

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