package io.gmss.fiscad.implementations.synchronisation;

import io.gmss.fiscad.entities.user.User;
import io.gmss.fiscad.interfaces.statistique.StatistiquesService;
import io.gmss.fiscad.interfaces.user.UserService;
import io.gmss.fiscad.paylaods.response.StatEnqueteAdminDecoupageResponse;
import io.gmss.fiscad.paylaods.response.StatEnqueteAdminStructureResponse;
import io.gmss.fiscad.paylaods.response.StatEnqueteParBlocResponse;
import io.gmss.fiscad.paylaods.response.StatEnqueteParStatutResponse;
import io.gmss.fiscad.repositories.infocad.metier.EnqueteRepository;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class StatistiquesServiceImpl implements StatistiquesService {
    private Authentication authentication;
    private final UserService userService;
    private final EnqueteRepository enqueteRepository;

    public StatistiquesServiceImpl(UserService userService, EnqueteRepository enqueteRepository) {
        this.userService = userService;
        this.enqueteRepository = enqueteRepository;
    }

    @Override
    public List<StatEnqueteParStatutResponse> getStatEnqueteParStatut() {
        String userName = "";
        List<StatEnqueteParStatutResponse> statEnqueteParStatutResponse = new ArrayList<>();
        try {
            authentication = SecurityContextHolder.getContext().getAuthentication();
            userName = authentication.getName();
            User user = userService.getUserByUsername(userName);
            statEnqueteParStatutResponse = user.isAdmin() ? enqueteRepository.getStatEnqueteParStatut() : enqueteRepository.getStatEnqueteParStatut(user.getId());
            return statEnqueteParStatutResponse;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<StatEnqueteAdminDecoupageResponse> getStatEnqueteAdminDecoupage(Long idCommune) {
        return enqueteRepository.getStatEnqueteParDecoupage(idCommune);
    }

    @Override
    public List<StatEnqueteAdminStructureResponse> getStatEnqueteAdminStructure() {
        return enqueteRepository.getStatEnqueteParStructure();
    }

    @Override
    public List<StatEnqueteParBlocResponse> getStatBloc() {
        String userName = "";
        try {
            authentication = SecurityContextHolder.getContext().getAuthentication();
            userName = authentication.getName();
            User user = userService.getUserByUsername(userName);
            return enqueteRepository.getStatEnqueteParBloc(user.getId());
        } catch (Exception e) {
            return new ArrayList<>();
        }

    }
}
