package com.ibtp.kontor.tradingcards.dal;

import com.ibtp.kontor.dal.BaseImpl;
import com.ibtp.kontor.tradingcards.entity.PositionEntity;

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

/**
 * Created by tpeetz on 27.01.2015.
 */
public class PositionImpl extends BaseImpl implements PositionDao {

    @Override
    public PositionEntity getById(Long id) {
        Query q = getEntityManager().createNamedQuery("Position.findById");
        q.setParameter("id", id);
        return (PositionEntity)q.getSingleResult();
    }

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

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

    @Override
    public Collection<PositionEntity> findAll() {
        Query q = getEntityManager().createNamedQuery("Position.findAll");
        return q.getResultList();
    }

    @Override
    public PositionEntity addPosition(String name) {
        PositionEntity position = new PositionEntity(name);
        store(position);
        return position;
    }

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

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