package com.ibtp.kontor.tradingcards.dal;

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

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

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

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

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

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

    @Override
    public Collection<PositionEntity> findAll() {
        Query query = getEntityManager().createNamedQuery("Position.findAll");
        return query.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();
    }
}
