package com.wishurgift.service.bean;

import com.wishurgift.persistence.data.StatsStatus;
import com.wishurgift.persistence.data.StatsWishlist;
import com.wishurgift.persistence.entity.User;
import com.wishurgift.persistence.repository.ContactRepository;
import com.wishurgift.persistence.repository.StatisticRepository;
import com.wishurgift.persistence.repository.UserRepository;
import com.wishurgift.service.ContactService;
import com.wishurgift.service.StatisticService;
import com.wishurgift.service.dto.StatisticDTO;
import com.wishurgift.service.dto.UserDTO;
import com.wishurgift.service.dto.transformer.UserTransformer;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.util.Optional;

@Stateless
public class StatisticServiceBean implements StatisticService {

    @Inject
    StatisticRepository repository;

    @Inject
    ContactRepository contactRepository;

    @Inject
    UserRepository userRepository;

    @Inject
    ContactService contactService;

    @Override
    public StatisticDTO getStatistic(UserDTO principal, long id) {
        // Recuperation de l'utilisateur
        Optional<User> optionalUser = userRepository.findById(id);
        if (!optionalUser.isPresent()) {
            return null;
        }
        User user = optionalUser.get();
        // Verifivation si l'utilisateur peut accèder aux données
        StatisticDTO statisticDTO = null;
        if (principal.getId() == id) {
            statisticDTO = getStatistic(user);
        } else if (contactService.isContact(principal, UserTransformer.entityToDto(user))) {
            statisticDTO = getStatistic(user);
        }
        return statisticDTO;
    }

    private StatisticDTO getStatistic(User user) {
        StatsWishlist statsWishlist = repository.wishlistStats(user);
        StatsStatus statsStatus = repository.statusStats(user);
        long contact = contactRepository.countAllContact(user);
        return new StatisticDTO(statsWishlist, statsStatus, contact);
    }

}
