package com.wishurgift.persistence.repository.bean;

import com.wishurgift.persistence.data.StatsStatus;
import com.wishurgift.persistence.data.StatsWishlist;
import com.wishurgift.persistence.entity.User;
import com.wishurgift.persistence.repository.StatisticRepository;
import com.wishurgift.utils.Constant;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

@Stateless
public class StatisticRepositoryBean implements StatisticRepository {

    public static final String NB_STATUS = "select count(distinct e) " +
            "from Element e " +
            "where e.wishlist.user = :user " +
            "And e.status = :status";

    private static final String WISHLIST_STATS = "select new com.wishurgift.persistence.data." +
            "StatsWishlist(count(distinct w), count(distinct e), avg(e.price), min(e.price), max(e.price)) " +
            "from Wishlist w left join w.elements e " +
            "where w.user = :user";

    @PersistenceContext(unitName = "wishurgiftPU")
    protected EntityManager entityManager;

    @Override
    public StatsWishlist wishlistStats(User user) {
        TypedQuery<StatsWishlist> query = entityManager.createQuery(WISHLIST_STATS, StatsWishlist.class);
        query.setParameter("user", user);
        return query.getSingleResult();
    }

    @Override
    public StatsStatus statusStats(User user) {
        StatsStatus stats = new StatsStatus();
        // Nb idea
        TypedQuery<Long> query = entityManager.createQuery(NB_STATUS, Long.class);
        query.setParameter("user", user);
        query.setParameter("status", Constant.Status.IDEA.getName());
        stats.setNbIdea(query.getSingleResult());
        // Nb crush
        query = entityManager.createQuery(NB_STATUS, Long.class);
        query.setParameter("user", user);
        query.setParameter("status", Constant.Status.CRUSH.getName());
        stats.setNbCrush(query.getSingleResult());
        // Nb reserved
        query = entityManager.createQuery(NB_STATUS, Long.class);
        query.setParameter("user", user);
        query.setParameter("status", Constant.Status.RESERVED.getName());
        stats.setNbReserved(query.getSingleResult());
        // Nb purchased
        query = entityManager.createQuery(NB_STATUS, Long.class);
        query.setParameter("user", user);
        query.setParameter("status", Constant.Status.PURCHASED.getName());
        stats.setNbPurchased(query.getSingleResult());
        // retour
        return stats;
    }

}
