package com.ibtp.kontor.comics.dal;

import com.ibtp.kontor.comics.entity.ArtistEntity;
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 16.01.2015.
 */
public class ArtistImpl extends BaseImpl implements ArtistDao {

    public ArtistImpl() {}

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

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

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

    }

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

    @Override
    public ArtistEntity addArtist(String name) {
        ArtistEntity artist = new ArtistEntity(name);
        artist = store(artist);
        return artist;
    }

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

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