package com.ibtp.kontor.tradingcards.dal;

import com.ibtp.kontor.dal.BaseImpl;
import com.ibtp.kontor.tradingcards.entity.SportEntity;
import com.ibtp.kontor.tradingcards.entity.TeamEntity;

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

/**
 * Created by TPEETZ on 19.01.2015.
 */
public class TeamImpl extends BaseImpl implements TeamDao {

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

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

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

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

    @Override
    public TeamEntity addTeam(String name, SportEntity sport) {
        TeamEntity team = new TeamEntity(name);
        team.setSport(sport);
        store(team);
        return team;
    }

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

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