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.ActiveIngredientRecomendation;
import tutorial.core.repositories.ActiveIngredientRecomendationRepo;

/**
 * 
 * @author Xavier
 */
@Repository
public class JpaActiveIngredientRecomendationRepo implements ActiveIngredientRecomendationRepo {
    @PersistenceContext
    private EntityManager em;

    /**
     *
     * @param id
     * @return
     */
    @Override
    public ActiveIngredientRecomendation findActiveIngredientRecomendation(Long id) {
        return em.find(ActiveIngredientRecomendation.class, id);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public ActiveIngredientRecomendation deleteActiveIngredientRecomendation(Long id) {
        ActiveIngredientRecomendation recomendation = em.find(ActiveIngredientRecomendation.class, id);
        em.remove(recomendation);
        return recomendation;
    }

    @Override
    public ActiveIngredientRecomendation updateActiveIngredientRecomendation(Long id, ActiveIngredientRecomendation data) {
        ActiveIngredientRecomendation recomendation = em.find(ActiveIngredientRecomendation.class, id);
        recomendation.setAdjustDose(data.getAdjustDose());
        recomendation.setClinicalCare(data.getClinicalCare());
        recomendation.setGlomerularFiltrationRateRange(data.getGlomerularFiltrationRateRange());
        recomendation.setMaxGlomerularFiltrationRate(data.getMaxGlomerularFiltrationRate());
        recomendation.setMinGlomerularFiltrationRate(data.getMinGlomerularFiltrationRate());
        recomendation.setRisk(data.getRisk());
        return recomendation;
    }

    @Override
    public ActiveIngredientRecomendation createActiveIngredientRecomendation(ActiveIngredientRecomendation data) {
        em.persist(data);
        return data;
    }

    //TODO REPASSAR (les recomanacions no tenen ID)
    @Override
    public List<ActiveIngredientRecomendation> findByActiveIngredientId(Long activeIngredientId) {
        Query query = em.createQuery("SELECT b FROM ActiveIngredientRecomendation b WHERE b.activeIngredient.id = :id");
        query.setParameter("id", activeIngredientId);
        return query.getResultList();
    }

    @Override
    public void deleteAllRecomendations() {
        Query query = em.createQuery("DELETE from ActiveIngredientRecomendation");
        int numDeletedRecomendations = query.executeUpdate();
    }
}
