package tutorial.core.repositories.jpa;

import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import tutorial.core.models.entities.ActiveIngredient;
import tutorial.core.repositories.ActiveIngredientRepo;

/**
 * 
 * @author Xavier
 */
@Repository
public class JpaActiveIngredientRepo implements ActiveIngredientRepo {
    @PersistenceContext
    private EntityManager em;

    @Override
    public ActiveIngredient createActiveIngredient(ActiveIngredient data) {
        em.persist(data);
        return data;
    }

    @Override
    public List<ActiveIngredient> findAllActiveIngredients() {
        Query query = em.createQuery("SELECT b from ActiveIngredient b");
        return query.getResultList();
    }

    @Override
    public ActiveIngredient findActiveIngredient(Long id) {
        return em.find(ActiveIngredient.class, id);
    }

    @Override
    public ActiveIngredient findActiveIngredientByName(String name) {
        Query query = em.createQuery("SELECT b from ActiveIngredient b where b.name= :name");
        query.setParameter("name", name);
        List<ActiveIngredient> activeIngredients = query.getResultList();
        if(activeIngredients.isEmpty()) {
            return null;
        } else {
            return activeIngredients.get(0);
        }
    }

    /*
    @Override
    public List<ActiveIngredient> findActiveIngredientByAccount(Long accountId) {
        Query query = em.createQuery("SELECT b from ActiveIngredient b where b.owner.id= :accountId");
        query.setParameter("accountId", accountId);
        return query.getResultList();
    }
    */

    @Override
    public void deleteAllActiveIngredients() {
        Query query = em.createQuery("DELETE from ActiveIngredient");
        int numDeletedActiveIngredients = query.executeUpdate();
    }
}
