package io.gmss.fiscad.implementations.synchronisation;

import io.gmss.fiscad.entities.infocad.metier.Tpe;
import io.gmss.fiscad.entities.user.User;
import io.gmss.fiscad.interfaces.synchronisation.RestaurationService;
import io.gmss.fiscad.interfaces.user.UserService;
import io.gmss.fiscad.paylaods.response.restoration.*;
import io.gmss.fiscad.repositories.infocad.metier.*;
import io.gmss.fiscad.repositories.infocad.parametre.PersonneRepository;
import io.gmss.fiscad.repositories.rfu.metier.*;
import io.gmss.fiscad.service.FileStorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
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.Base64;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RestaurationServiceImpl implements RestaurationService {
    public final ActeurConcerneRepository acteurConcerneRepository;
    public final EnqueteRepository enqueteRepository;
    public final PersonneRepository personneRepository;
    public final ParcelleRepository parcelleRepository;
    public final MembreGroupeRepository membreGroupeRepository;
    public final PieceRepository pieceRepository;
    public final UploadRepository uploadRepository;
    private final FileStorageService fileStorageService;
    private final TpeRepository tpeRepository;
    private final UserService userService;
    private Authentication authentication;
    private final BatimentRepository batimentRepository;
    private final EnqueteBatimentRepository enqueteBatimentRepository;
    private final CaracteristiqueBatimentRepository caracteristiqueBatimentRepository;
    private final CaracteristiqueUniteLogementRepository caracteristiqueUniteLogementRepository;
    private final CaracteristiqueParcelleRepository caracteristiqueParcelleRepository;
    private final EnqueteUniteLogementRepository enqueteUniteLogementRepository;
    private final UniteLogementRepository uniteLogementRepository;


    @Override
    public List<ActeurConcernePayLoad> getActeurConcernes(Long terminaleId) {
        return acteurConcerneRepository.getActeurConcerneByTerminalId(terminaleId);
    }

    @Override
    public List<EnquetePayLoad> getEnquete(Long terminaleId) {

        return enqueteRepository.getEnqueteByTerminalId(terminaleId);
    }

    @Override
    public List<PersonnePayLoad> getPersonne(Long terminaleId) {
        return personneRepository.getPersonnesByTerminalId(terminaleId);
    }

    @Override
    public List<ParcellePayLoad> getParcelle(Long terminaleId) {

        return parcelleRepository.getParcellesByTerminalId(terminaleId);
    }

    @Override
    public List<PiecePayLoad> getPieces(Long terminaleId) {

        return pieceRepository.getPiecesByTerminalId(terminaleId);
    }

    @Override
    public List<MembreGroupePayLoad> getMembreGroupe(Long terminaleId) {

        return membreGroupeRepository.getMembreGroupeByTerminalId(terminaleId);
    }

    @Override
    public List<io.gmss.fiscad.paylaods.request.UploadPayLoad> getUpload(Long terminaleId) {
        List<UploadPayLoad> uploadPayLoads = uploadRepository.getUploadByTerminalId(terminaleId);

        List<io.gmss.fiscad.paylaods.request.UploadPayLoad> uploadPayLoadsOut = new ArrayList<>();
        uploadPayLoads.forEach(uploadPayLoad -> {
            io.gmss.fiscad.paylaods.request.UploadPayLoad uploadPayLoadLocal = new io.gmss.fiscad.paylaods.request.UploadPayLoad();
            uploadPayLoadLocal.setTerminalId(uploadPayLoad.getTerminalId());
            String inputStream = getUploadFile(uploadPayLoad);
            uploadPayLoadLocal.setFileBase64(inputStream);
            uploadPayLoadLocal.setIdBackend(uploadPayLoad.getIdBackend());
            uploadPayLoadLocal.setPieceId(uploadPayLoad.getPieceId());
            uploadPayLoadLocal.setSynchronise(uploadPayLoad.getSynchronise());
            uploadPayLoadLocal.setMembreGroupeId(uploadPayLoad.getMembreGroupeId());
            uploadPayLoadLocal.setExternalKey(uploadPayLoad.getExternalKey());
            uploadPayLoadLocal.setBlocId(uploadPayLoad.getBlocId());
            uploadPayLoadLocal.setFilePath(uploadPayLoad.getFilePath());
            uploadPayLoadLocal.setEnqueteId(uploadPayLoad.getEnqueteId());
            uploadPayLoadLocal.setMax_numero_acteur_concerne_id(uploadPayLoad.getMax_numero_acteur_concerne_id());
            uploadPayLoadLocal.setMax_numero_piece_id(uploadPayLoad.getMax_numero_piece_id());
            uploadPayLoadLocal.setMax_numero_upload_id(uploadPayLoad.getMax_numero_upload_id());
            uploadPayLoadLocal.setName(uploadPayLoad.getName());
            uploadPayLoadLocal.setObservation(uploadPayLoad.getObservation());
            uploadPayLoadsOut.add(uploadPayLoadLocal);
        });
        return uploadPayLoadsOut;
    }

    @Override
    public List<BatimentPayload> getBatiment(Long terminalId) {
        return batimentRepository.getBatimentByTerminalId(terminalId);
    }

    @Override
    public List<EnqueteBatimentPayLoad> getEnqueteBatiment(Long terminalId) {
        return enqueteBatimentRepository.getEnqueteBatimentByTerminalId(terminalId);
    }

    @Override
    public List<CaracateristiqueParcellePayLoads> getCaracateristiqueParcelle(Long terminalId) {
        return caracteristiqueParcelleRepository.getCaracteristiqueParcelleByTerminalId(terminalId);
    }

    @Override
    public List<CaracateristiqueBatimentPayLoads> getCaracateristiqueBatiment(Long terminalId) {
        return caracteristiqueBatimentRepository.getCaracteristiqueBatimentByTerminalId(terminalId);
    }

    @Override
    public List<CaracteristiqueUniteLogementPayLoad> getCaracateristiqueUniteLogement(Long terminalId) {
        return caracteristiqueUniteLogementRepository.getCaracteristiqueUniteLogementByTerminalId(terminalId);
    }

    @Override
    public List<EnqueteUniteLogementPayLoad> getEnqueteUniteLogement(Long terminalId) {
        return enqueteUniteLogementRepository.getEnqueteUniteLogementByTerminalId(terminalId);
    }

    @Override
    public List<UniteLogementPayLoad> getUniteLogement(Long terminalId) {
        return uniteLogementRepository.getUniteLogementByTerminalId(terminalId);
    }

    private String getUploadFile(UploadPayLoad uploadPayLoad) {

        try {
            Resource resource = fileStorageService.loadFileAsResource(uploadPayLoad.getFileBackendName());
            final var bytes = resource.getInputStream().readAllBytes();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            System.out.println("ERREUR" + e.getMessage());
            //throw new RuntimeException(e);
            return null;
        }
    }


    public List<Tpe> getTpeListByCurrentUser() {
        try {
            authentication = SecurityContextHolder.getContext().getAuthentication();
            String userName = authentication.getName();
            User user = userService.getUserByUsername(userName);
            return tpeRepository.getTpeByUserId(user.getId());
        } catch (Exception e) {
            return new ArrayList<>();
        }

    }
}
