package io.gmss.fiscad.implementations.synchronisation;

import io.gmss.fiscad.entities.decoupage.Commune;
import io.gmss.fiscad.entities.decoupage.Nationalite;
import io.gmss.fiscad.entities.decoupage.Quartier;
import io.gmss.fiscad.entities.infocad.metier.*;
import io.gmss.fiscad.entities.infocad.parametre.*;
import io.gmss.fiscad.entities.metadata.*;
import io.gmss.fiscad.entities.rfu.metier.*;
import io.gmss.fiscad.entities.rfu.parametre.Caracteristique;
import io.gmss.fiscad.entities.rfu.parametre.TypeCaracteristique;
import io.gmss.fiscad.entities.rfu.parametre.ZoneRfu;
import io.gmss.fiscad.entities.user.User;
import io.gmss.fiscad.enums.*;
import io.gmss.fiscad.interfaces.infocad.metier.ParcelleGeomService;
import io.gmss.fiscad.interfaces.synchronisation.SynchronisationService;
import io.gmss.fiscad.interfaces.user.UserService;
import io.gmss.fiscad.paylaods.request.*;
import io.gmss.fiscad.paylaods.response.*;
import io.gmss.fiscad.repositories.decoupage.*;
import io.gmss.fiscad.repositories.infocad.metier.*;
import io.gmss.fiscad.repositories.infocad.parametre.*;
import io.gmss.fiscad.repositories.metadata.*;
import io.gmss.fiscad.repositories.rfu.metier.*;
import io.gmss.fiscad.repositories.rfu.parametre.CaracteristiqueRepository;
import io.gmss.fiscad.repositories.rfu.parametre.TypeCaracteristiqueRepository;
import io.gmss.fiscad.repositories.rfu.parametre.ZoneRfuRepository;
import io.gmss.fiscad.repositories.user.UserRepository;
import io.gmss.fiscad.service.FileStorageService;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class SynchronisationServiceImpl implements SynchronisationService {
    private Authentication authentication;
    private final UserService userService;
    private final DepartementRepository departementRepository;
    private final CommuneRepository communeRepository;
    private final ArrondissementRepository arrondissementRepository;
    private final QuartierRepository quartierRepository;
    private final BlocRepository blocRepository;
    private final ModeAcquisitionRepository modeAcquisitionRepository;
    private final NationaliteRepository nationaliteRepository;
    private final NatureDomaineRepository natureDomaineRepository;
    private final PositionRepresentationRepository positionRepresentationRepository;
    private final ProfessionRepository professionRepository;
    private final SituationMatrimonialeRepository situationMatrimonialeRepository;
    private final SourceDroitRepository sourceDroitRepository;
    private final StructureRepository structureRepository;
    private final TypeContestationRepository typeContestationRepository;
    private final TypeDomaineRepository typeDomaineRepository;
    private final TypePersonneRepository typePersonneRepository;
    private final TypePieceRepository typePieceRepository;
    private final TypeRepresentationRepository typeRepresentationRepository;
    private final MembreGroupeRepository membreGroupeRepository;
    private final PersonneRepository personneRepository;
    private final EnqueteRepository enqueteRepository;
    private final ParcelleRepository parcelleRepository;
    private final UserRepository userRepository;
    private final SituationGeographiqueRepository situationGeographiqueRepository;
    private final PieceRepository pieceRepository;
    private final ActeurConcerneRepository acteurConcerneRepository;
    private final UploadRepository uploadRepository;
    private final UploadMetaDataRepository uploadMetaDataRepository;
    private final PieceMetaDataRepository pieceMetaDataRepository;
    private final FileStorageService fileStorageService;
    private final TpeRepository tpeRepository;
    private final BatimentRepository batimentRepository;
    private final UniteLogementRepository uniteLogementRepository;
    private final ZoneRfuRepository zoneRfuRepository;

    private final CaracteristiqueRepository caracteristiqueRepository;
    private final TypeCaracteristiqueRepository typeCaracteristiqueRepository;

    private final EnqueteBatimentRepository enqueteBatimentRepository;
    private final EnqueteUniteLogementRepository enqueteUniteLogementRepository;

    private final CaracteristiqueBatimentRepository caracteristiqueBatimentRepository;
    private final CaracteristiqueParcelleRepository caracteristiqueParcelleRepository;
    private final CaracteristiqueUniteLogementRepository caracteristiqueUniteLogementRepository;
    private final ParcelleGeomService parcelleGeomService;

    private final MobileDataEnqueteBatimentRepository mobileDataEnqueteBatimentRepository;
    private final MobileDataActeurConcerneRepository mobileDataActeurConcerneRepository;
    private final MobileDataPersonneRepository mobileDataPersonneRepository;
    private final MobileDataMembreGroupeRepository mobileDataMembreGroupeRepository;
    private final MobileDataPieceRepository mobileDataPieceRepository;
    private final MobileDataUploadRepository mobileDataUploadRepository;
    private final MobileDataEnqueteRepository mobileDataEnqueteRepository;
    private final MobileDataCaracteristiqueParcelleRepository mobileDataCaracteristiqueParcelleRepository;
    private final MobileDataEnqueteUniteLogementRepository mobileDataEnqueteUniteLogementRepository;
    private final MobileDataCaracteristiqueBatimentRepository mobileDataCaracteristiqueBatimentRepository;
    private final MobileDataCaracteristiqueUniteLogementRepository mobileDataCaracteristiqueUniteLogementRepository;
    private final MobileDataUniteLogementRepository mobileDataUniteLogementRepository;
    private final MobileDataParcelleRepository mobileDataParcelleRepository;
    @Value("${io.gmss.fiscad.profile}")
    private String profile;

    @Override
    public UserDecoupageSyncResponses getDecoupageAdminUserConnecter() {
        authentication = SecurityContextHolder.getContext().getAuthentication();
        String userName = authentication.getName();

        User user = userService.getUserByUsername(userName);
        List<DepartementSyncResponse> departementSyncResponses =
                departementRepository.getDepartementResponse();

        List<CommuneSyncResponse> communeSyncResponses =
                communeRepository.getCommuneResponse();

        List<ArrondissementSyncResponse> arrondissementSyncResponses =
                arrondissementRepository.getArrondissementResponse(user.getStructure().getId());

        List<QuartierSyncResponse> quartierSyncResponses =
                quartierRepository.getQuartierResponse(user.getStructure().getId());

        List<BlocSyncResponse> blocSyncResponses = new ArrayList<>();
        System.out.println(profile);
        if (profile.equals(ProfileApp.ABOMEY.toString().toLowerCase())) {
            System.out.println("ABOMEY");
            if (user.getStructure() != null) {
                System.out.println(user.getStructure().getId());
                blocSyncResponses =
                        blocRepository.getBlocResponse(user.getStructure().getId());
            }
        }

        if (profile.equals(ProfileApp.DGI.toString().toLowerCase())) {
            System.out.println("DGI");
            if (user.getIdSecteurCourant() != null) {
                blocSyncResponses =
                        blocRepository.getBlocSecteurResponse(user.getStructure().getId(), user.getIdSecteurCourant());
            }
        }

        UserDecoupageSyncResponses userDecoupageSyncResponses = new UserDecoupageSyncResponses();
        userDecoupageSyncResponses.setDepartementSyncResponses(departementSyncResponses);
        userDecoupageSyncResponses.setCommuneSyncResponses(communeSyncResponses);
        userDecoupageSyncResponses.setArrondissementSyncResponses(arrondissementSyncResponses);
        userDecoupageSyncResponses.setQuartierSyncResponses(quartierSyncResponses);
        userDecoupageSyncResponses.setBlocSyncResponses(blocSyncResponses);
        return userDecoupageSyncResponses;
    }

    @Override
    public ReferencesSyncResponses getReferencesSyncResponses() {
        ReferencesSyncResponses referencesSyncResponses = new ReferencesSyncResponses();

        List<TypeRepresentation> typeRepresentationSyncResponses = typeRepresentationRepository.findAll();
        List<TypePiece> typePieceSyncResponses = typePieceRepository.findAll();
        List<TypePersonne> typePersonneSyncResponses = typePersonneRepository.findAll();
        List<TypeDomaine> typeDomaineSyncResponses = typeDomaineRepository.findAll();
        List<TypeContestation> typeContestationSyncResponses = typeContestationRepository.findAll();
        // List<Structure> structureSyncResponses = structureRepository.findAll();
        //List<SourceDroit> sourceDroitResponses = sourceDroitRepository.findAll();
        List<SourceDroitsSyncResponse> sourceDroitSyncResponses = sourceDroitRepository.getSourceDroitSyncResponse();
        List<SituationMatrimoniale> situationMatrimonialeSyncResponses = situationMatrimonialeRepository.findAll();
        List<Profession> professionSyncResponses = professionRepository.findAll();
        List<PositionRepresentation> positionRepresentationSyncResponses = positionRepresentationRepository.findAll();
        List<NatureDomaineSyncResponse> natureDomaineSyncResponses = natureDomaineRepository.getNatureDomaineResponse();
        List<Nationalite> nationaliteSyncResponses = nationaliteRepository.findAll();
        List<ModeAcquisition> modeAcquisitionSyncResponses = modeAcquisitionRepository.findAll();
        List<ModesAcquisitionSourceSyncResponse> modeAcquisitionSourceSyncResponses = sourceDroitRepository.getModeAcquitionSourceSyncResponse();
        List<SituationGeographique> situationGeographiques = situationGeographiqueRepository.findAll();
        List<TypePersonneNatureDomaineSyncResponse> typePersonneNatureDomaineSyncResponses = natureDomaineRepository.getTypePersonneNatureDomaineSyncResponse();
        List<ModesAcquisitionTypePersonneSyncResponse> modesAcquisitionTypePersonneSyncResponses = modeAcquisitionRepository.getModeAcquisitionTypePersonne();

        List<Caracteristique> caracteristiquesSyncResponses = caracteristiqueRepository.findAllByActifIsTrue();
        List<TypeCaracteristique> typeCaracteristiquesSyncResponses = typeCaracteristiqueRepository.findAllByActifIsTrue();
        List<ZoneRfuSyncResponse> zoneRfuSyncResponses = zoneRfuRepository.getZoneRfuResponse();



        referencesSyncResponses.setNatureDomaineSyncResponses(natureDomaineSyncResponses);
        referencesSyncResponses.setNationaliteSyncResponses(nationaliteSyncResponses);
        referencesSyncResponses.setModeAcquisitionSyncResponses(modeAcquisitionSyncResponses);
        referencesSyncResponses.setProfessionSyncResponses(professionSyncResponses);
        referencesSyncResponses.setSituationMatrimonialeSyncResponses(situationMatrimonialeSyncResponses);
        referencesSyncResponses.setPositionRepresentationSyncResponses(positionRepresentationSyncResponses);
        referencesSyncResponses.setSourceDroitSyncResponses(sourceDroitSyncResponses);
        //referencesSyncResponses.setStructureSyncResponses(structureSyncResponses);
        referencesSyncResponses.setTypeDomaineSyncResponses(typeDomaineSyncResponses);
        referencesSyncResponses.setTypePersonneSyncResponses(typePersonneSyncResponses);
        referencesSyncResponses.setTypeContestationSyncResponses(typeContestationSyncResponses);
        referencesSyncResponses.setTypePieceSyncResponses(typePieceSyncResponses);
        referencesSyncResponses.setTypeRepresentationSyncResponses(typeRepresentationSyncResponses);
        referencesSyncResponses.setSituationSyncGeographiques(situationGeographiques);
        referencesSyncResponses.setModesAcquisitionSourceSyncResponses(modeAcquisitionSourceSyncResponses);
        referencesSyncResponses.setTypePersonneNatureDomaineSyncResponses(typePersonneNatureDomaineSyncResponses);
        referencesSyncResponses.setModesAcquisitionTypePersonneSyncResponses(modesAcquisitionTypePersonneSyncResponses);

        referencesSyncResponses.setCaracteristiquesSyncResponses(caracteristiquesSyncResponses);
        referencesSyncResponses.setTypeCaracteristiquesSyncResponses(typeCaracteristiquesSyncResponses);
        referencesSyncResponses.setZoneRfuSyncResponses(zoneRfuSyncResponses);

        return referencesSyncResponses;
    }

    @Override
    public SyncEnqueteAllDataResponse syncEnqueteAllData(EnqueteAllDataPayload enqueteAllDataPayload) {
        List<SyncResponse> personnesSyncResp = syncPersonnes(enqueteAllDataPayload.getPersonnes());
        List<SyncResponse> membreGroupesResp = syncMembreGroupe(enqueteAllDataPayload.getMembreGroupes());
        List<SyncResponse> parcelleSyncResp = syncParcelle(enqueteAllDataPayload.getParcelle());
        List<SyncResponse> enqueteSyncResp = syncEnquete(enqueteAllDataPayload.getEnquetes());
        List<SyncResponse> acteurConcernesSyncResp = syncActeurConcerne(enqueteAllDataPayload.getActeurConcernes());
        List<SyncResponse> pieceSyncResp = syncPiece(enqueteAllDataPayload.getPieces());

        SyncEnqueteAllDataResponse syncEnqueteAllDataResponse = new SyncEnqueteAllDataResponse();
        syncEnqueteAllDataResponse.setPersonneSynResponses(personnesSyncResp);
        syncEnqueteAllDataResponse.setMembreGroupeSynResponses(membreGroupesResp);
        syncEnqueteAllDataResponse.setParcelleSynResponses(parcelleSyncResp);
        syncEnqueteAllDataResponse.setEnqueteSynResponses(enqueteSyncResp);
        syncEnqueteAllDataResponse.setActeurConcerneSynResponses(acteurConcernesSyncResp);
        syncEnqueteAllDataResponse.setPieceSynResponses(pieceSyncResp);
        return syncEnqueteAllDataResponse;
    }

    @Override
    public List<SyncResponse> syncPersonnes(List<PersonnePayLoad> personnePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (personnePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune personne à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }

        //saveMobileData(personnePayLoads,TypeObjet.PERSONNE);

        personnePayLoads.forEach(personnePayLoad -> {
            try {
                System.out.println(personnePayLoad);
                if (personnePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(personnePayLoad.getIdBackend(),
                            personnePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(personnePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(personnePayLoad.getIdBackend(),
                                personnePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                Personne personne = new Personne();
                SyncResponse syncResponse = new SyncResponse();
                personnePayLoad.setSynchronise(true);
                if (personnePayLoad.getIdBackend() != null && personnePayLoad.getIdBackend() != 0) {
                    Optional<Personne> optionalPersonne = personneRepository.findById(personnePayLoad.getIdBackend());
                    if (optionalPersonne.isPresent()) {
                        personne = optionalPersonne.get();
                        System.out.println("SUPRESSION FROM PERSONNE "+personne.getId());
                        deleteFromPersonne(personne.getId());
                    }else{
                        personnePayLoad.setIdBackend(null);
                    }
                    personne = getPersonneFromPersonnePayLoad(personne, personnePayLoad);
                    personne = personneRepository.save(personne);
                    personnePayLoad.setIdBackend(personne.getId());
                }
                else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(personnePayLoad.getExternalKey(),personnePayLoad.getTerminalId());
                    if(optionalPersonne.isPresent()){
                        System.out.println("SUPRESSION FROM PERSONNE "+personne.getId());
                        deleteFromPersonne(optionalPersonne.get().getId());
                        personne = optionalPersonne.get();
                        personne = getPersonneFromPersonnePayLoad(personne, personnePayLoad);
                        personne = personneRepository.save(personne);
                        personnePayLoad.setIdBackend(personne.getId());
                    }else {
                        personne = getPersonneFromPersonnePayLoad(personne, personnePayLoad);
                        personne = personneRepository.save(personne);
                        personnePayLoad.setIdBackend(personne.getId());
                    }
                }
                syncResponse.setObservation(personnePayLoad.getObservation());
                syncResponse.setExternalKey(personnePayLoad.getExternalKey());
                syncResponse.setSynchronise(personnePayLoad.isSynchronise());
                syncResponse.setIdBackend(personnePayLoad.getIdBackend());
                System.out.println(syncResponse);
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(personnePayLoad.getIdBackend(),
                        personnePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    private <T> void saveMobileData(List<T> payloads, TypeObjet typeObjet) {
        switch (typeObjet){
            case PERSONNE -> {
                payloads.forEach(payLoad -> {
                    PersonnePayLoad p=  (PersonnePayLoad) payLoad ;
                    MobileDataPersonne mobileDataPersonne=new MobileDataPersonne();
                    mobileDataPersonne.setPersonnePayLoad(p);

                    Optional<MobileDataPersonne> optionalMobileDataPersonne=
                            mobileDataPersonneRepository.findByPersonnePayLoad_TerminalIdAndPersonnePayLoad_ExternalKey(p.getTerminalId(),p.getExternalKey());
                    if(optionalMobileDataPersonne.isPresent()){
                        mobileDataPersonne=optionalMobileDataPersonne.get();
                    }

                });
            }
            case MEMBREGROUPE -> {

            }
            case ACTEURCONCERNER -> {

            }
            case PIECE -> {

            }
            case UPLOAD -> {

            }
            case BATIMENT -> {

            }
            case UNITELOGEMENT -> {

            }
            case ENQUETEBATIMENT -> {

            }
            case ENQUETEUNITELOGEMENT -> {

            }
            case CARACTERISTIQUEPARCELLE -> {

            }

            case CARACTERISTIQUEBATIMENT -> {

            }
            case CARACTERISTIQUEUNITELOGEMENT -> {

            }
            case PARCELLE -> {

            }
        }

    }


    private void deleteFromPersonne(Long idBackend) {
        uploadRepository.deleteUploadByMembreGroupe_PersonneRepresantee_Id(idBackend);
        uploadRepository.deleteUploadByPiece_Personne_Id(idBackend);
        uploadRepository.deleteUploadByPersonne_Id(idBackend);
        membreGroupeRepository.deleteMembreGroupeByPersonneRepresantante_Id(idBackend);
        pieceRepository.deletePieceByPersonne_Id(idBackend);
    }

    private Personne getPersonneFromPersonnePayLoad(Personne personne, PersonnePayLoad personnePayLoad) {
        if (personnePayLoad.getCommuneId() != null) {
            Optional<Commune> optionalCommune = communeRepository.findById(personnePayLoad.getCommuneId());
            personne.setCommune(optionalCommune.orElse(null));
        }
        if (personnePayLoad.getNationaliteId() != null) {
            Optional<Nationalite> optionalNationalite = nationaliteRepository.findById(personnePayLoad.getNationaliteId());
            personne.setNationalite(optionalNationalite.orElse(null));
        }
        if (personnePayLoad.getProfessionId() != null) {
            Optional<Profession> optionalProfession = professionRepository.findById(personnePayLoad.getProfessionId());
            personne.setProfession(optionalProfession.orElse(null));
        }
        if (personnePayLoad.getTypePersonneId() != null) {
            Optional<TypePersonne> optionalTypePersonne = typePersonneRepository.findById(personnePayLoad.getTypePersonneId());
            personne.setTypePersonne(optionalTypePersonne.orElse(null));
        } else {
            Optional<TypePersonne> optionalTypePersonne = typePersonneRepository.findFirstByCategorie(Categorie.PERSONNE_PHYSIQUE);
            personne.setTypePersonne(optionalTypePersonne.orElse(null));

        }
        if (personnePayLoad.getSituationMatrimonialeId() != null) {
            Optional<SituationMatrimoniale> optionalSituationMatrimoniale = situationMatrimonialeRepository.findById(personnePayLoad.getSituationMatrimonialeId());
            personne.setSituationMatrimoniale(optionalSituationMatrimoniale.orElse(null));
        }
        if (personnePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(personnePayLoad.getTerminalId());
            personne.setTerminal(optionalTpe.orElse(null));
        }

        personne.setCategorie(personnePayLoad.getCategorie());
        personne.setAdresse(personnePayLoad.getAdresse());
        personne.setIfu(personnePayLoad.getIfu());
        personne.setDateNaissanceOuConsti(personnePayLoad.getDateNaissanceOuConsti());
        personne.setLieuNaissance(personnePayLoad.getLieuNaissance());
        personne.setNomOuSigle(personnePayLoad.getNomOuSigle());
        personne.setNpi(personnePayLoad.getNpi());
        personne.setNumRavip(personnePayLoad.getNumRavip());
        personne.setPrenomOuRaisonSociale(personnePayLoad.getPrenomOuRaisonSociale());
        personne.setTel1(personnePayLoad.getTel1());
        personne.setTel2(personnePayLoad.getTel2());
        personne.setExternalKey(personnePayLoad.getExternalKey());

        personne.setHaveRepresentant(personnePayLoad.getHaveRepresentant());
        personne.setRavipQuestion(personnePayLoad.getRavipQuestion());
        personne.setAge(personnePayLoad.getAge());
        personne.setNomJeuneFille(personnePayLoad.getNomJeuneFille());
        personne.setNomMere(personnePayLoad.getNomMere());
        personne.setPrenomMere(personnePayLoad.getPrenomMere());
        personne.setIndicatifTel1(personnePayLoad.getIndicatifTel1());
        personne.setIndicatifTel2(personnePayLoad.getIndicatifTel2());
        personne.setSexe(personnePayLoad.getSexe());
        personne.setMustHaveRepresentant(personnePayLoad.getMustHaveRepresentant());
        personne.setFilePath(personnePayLoad.getFilePath());
        personne.setObservation(personnePayLoad.getObservation());
        return personne;
    }

    @Override
    public List<SyncResponse> syncMembreGroupe(List<MembreGroupePayLoad> membreGroupePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (membreGroupePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucun membre à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        membreGroupePayLoads.forEach(membreGroupePayLoad -> {
            try {
                if (membreGroupePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                            membreGroupePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(membreGroupePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                                membreGroupePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (membreGroupePayLoad.getPersonneRepresentanteId() == null) {
                    SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                            membreGroupePayLoad.getExternalKey(), false, "La personne représentante n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getPersonneRepresentanteId(), membreGroupePayLoad.getTerminalId());
                    if (optionalPersonne.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                                membreGroupePayLoad.getExternalKey(), false, "La personne représentante précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (membreGroupePayLoad.getPersonneRepresenteeId() == null) {
                    SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                            membreGroupePayLoad.getExternalKey(), false, "La personne représentée n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getPersonneRepresenteeId(), membreGroupePayLoad.getTerminalId());
                    if (optionalPersonne.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                                membreGroupePayLoad.getExternalKey(), false, "La personne représentée précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                MembreGroupe membreGroupe = new MembreGroupe();
                membreGroupePayLoad.setSynchronise(true);
                if (membreGroupePayLoad.getIdBackend() != null && membreGroupePayLoad.getIdBackend() != 0) {
                    Optional<MembreGroupe> optionalMembreGroupe = membreGroupeRepository.findById(membreGroupePayLoad.getIdBackend());
                    if (optionalMembreGroupe.isPresent()) {
                        membreGroupe = optionalMembreGroupe.get();
                    } else {
                        membreGroupePayLoad.setIdBackend(null);
                    }
                        membreGroupe = getMembreGroupeFromMembreGroupePayLoad(membreGroupe, membreGroupePayLoad);
                        membreGroupe = membreGroupeRepository.save(membreGroupe);
                        membreGroupePayLoad.setIdBackend(membreGroupe.getId());

                } else {
                    Optional<MembreGroupe> optionalMembreGroupe = membreGroupeRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getExternalKey(),membreGroupePayLoad.getTerminalId());
                    if (optionalMembreGroupe.isPresent()) {
                        membreGroupe=optionalMembreGroupe.get();
                        membreGroupe = getMembreGroupeFromMembreGroupePayLoad(membreGroupe, membreGroupePayLoad);
                        membreGroupe = membreGroupeRepository.save(membreGroupe);
                        membreGroupePayLoad.setIdBackend(membreGroupe.getId());
                    }else {
                        membreGroupe = getMembreGroupeFromMembreGroupePayLoad(membreGroupe, membreGroupePayLoad);
                        membreGroupe = membreGroupeRepository.save(membreGroupe);
                        membreGroupePayLoad.setIdBackend(membreGroupe.getId());
                    }
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(membreGroupePayLoad.getObservation());
                syncResponse.setExternalKey(membreGroupePayLoad.getExternalKey());
                syncResponse.setSynchronise(membreGroupePayLoad.isSynchronise());
                syncResponse.setIdBackend(membreGroupePayLoad.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(membreGroupePayLoad.getIdBackend(),
                        membreGroupePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }


    private MembreGroupe getMembreGroupeFromMembreGroupePayLoad(MembreGroupe membreGroupe, MembreGroupePayLoad membreGroupePayLoad) {
        if (membreGroupePayLoad.getPersonneRepresentanteId() != null) {
            Optional<Personne> optionalRepresentant = personneRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getPersonneRepresentanteId(), membreGroupePayLoad.getTerminalId());
            membreGroupe.setPersonneRepresantante(optionalRepresentant.orElse(null));
        }
        if (membreGroupePayLoad.getPersonneRepresenteeId() != null) {
            Optional<Personne> optionalRepresente = personneRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getPersonneRepresenteeId(), membreGroupePayLoad.getTerminalId());
            membreGroupe.setPersonneRepresantee(optionalRepresente.orElse(null));
        }

        if (membreGroupePayLoad.getPositionRepresentationId() != null) {
            Optional<PositionRepresentation> optionalPositionRepresentation = positionRepresentationRepository.findById(membreGroupePayLoad.getPositionRepresentationId());
            membreGroupe.setPositionRepresentation(optionalPositionRepresentation.orElse(null));
        }
        if (membreGroupePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(membreGroupePayLoad.getTerminalId());
            membreGroupe.setTerminal(optionalTpe.orElse(null));
        }

        if (membreGroupePayLoad.getTypeRepresentationId() != null) {
            Optional<TypeRepresentation> optionalTypeRepresentation = typeRepresentationRepository.findById(membreGroupePayLoad.getTypeRepresentationId());
            membreGroupe.setExternalKey(membreGroupePayLoad.getExternalKey());

        }

        if (membreGroupePayLoad.getEnqueteId() != null) {
            Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(membreGroupePayLoad.getEnqueteId(),membreGroupePayLoad.getTerminalId());
            membreGroupe.setExternalKey(membreGroupePayLoad.getExternalKey());
            membreGroupe.setEnqueteId(optionalEnquete.get().getId());
        }

        membreGroupe.setMax_numero_acteur_concerne_id(membreGroupePayLoad.getMax_numero_acteur_concerne_id());
        membreGroupe.setMax_numero_piece_id(membreGroupePayLoad.getMax_numero_piece_id());
        membreGroupe.setEnqueteExternalKey(membreGroupePayLoad.getEnqueteId());

        membreGroupe.setBlocId(membreGroupePayLoad.getBlocId());
        membreGroupe.setObservation(membreGroupePayLoad.getObservation());

        return membreGroupe;
    }

    @Override
    @Transactional
    public List<SyncResponse> syncEnquete(List<EnquetePayLoad> enquetePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (enquetePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune enquête à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        enquetePayLoads.forEach(enquetePayLoad -> {
                    System.out.println("ENQUETE A SUPPRIMER " +enquetePayLoad.getCodeParcelle());
                    deleteFromCodeParcelle(enquetePayLoad.getCodeParcelle());
                });

        enquetePayLoads.forEach(enquetePayLoad -> {
            try {
               // deleteFromCodeParcelle(enquetePayLoad.getCodeParcelle());
                if (enquetePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                            enquetePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(enquetePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                                enquetePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (enquetePayLoad.getUserId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                            enquetePayLoad.getExternalKey(), false, "L'enquêteur n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<User> optionalUser = userRepository.findById(enquetePayLoad.getUserId());
                    if (optionalUser.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                                enquetePayLoad.getExternalKey(), false, "L'enquêteur précisé n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enquetePayLoad.getZoneRfuId() != null)  {
                    Optional<ZoneRfu> optionalZoneRfu = zoneRfuRepository.findById(enquetePayLoad.getZoneRfuId());
                    if (optionalZoneRfu.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                                enquetePayLoad.getExternalKey(), false, "La zone rfu n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enquetePayLoad.getParcelleId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                            enquetePayLoad.getExternalKey(), false, "La parcelle n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByExternalKeyAndTerminal_Id(enquetePayLoad.getParcelleId(), enquetePayLoad.getTerminalId());
                    if (optionalParcelle.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                                enquetePayLoad.getExternalKey(), false, "La parcelle précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enquetePayLoad.getBlocId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                            enquetePayLoad.getExternalKey(), false, "Le bloc n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Bloc> optionalBloc = blocRepository.findById(enquetePayLoad.getBlocId());
                    if (optionalBloc.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                                enquetePayLoad.getExternalKey(), false, "Le bloc précisé n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                Enquete enquete = new Enquete();
                enquetePayLoad.setSynchronise(true);
                Optional<Enquete> optionalEnquete;
                if (enquetePayLoad.getIdBackend() != null && enquetePayLoad.getIdBackend() != 0) {
                    optionalEnquete = enqueteRepository.findById(enquetePayLoad.getIdBackend());
                } else {
                    optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(enquetePayLoad.getExternalKey(), enquetePayLoad.getTerminalId());
                }
                if (optionalEnquete.isPresent()) {
                    enquete = optionalEnquete.get();
                } else {
                    enquetePayLoad.setIdBackend(null);
                }
                enquete = getEnqueteFromEnquetePayLoad(enquete, enquetePayLoad);
                enquete.setStatutEnregistrement(StatutEnregistrement.NOUVELLE_INSERTION);
                enquete = enqueteRepository.save(enquete);
                enquetePayLoad.setIdBackend(enquete.getId());
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(enquetePayLoad.getObservation());
                syncResponse.setExternalKey(enquetePayLoad.getExternalKey());
                syncResponse.setSynchronise(enquetePayLoad.isSynchronise());
                syncResponse.setIdBackend(enquetePayLoad.getIdBackend());
                syncResponses.add(syncResponse);
                try{
                    if(enquete.getParcelle()!=null) {
                        parcelleGeomService.setStatutParcelleGeomFromEnquete(enquete);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(enquetePayLoad.getIdBackend(),
                        enquetePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    private void deleteFromEnquete(Long idBackend) {
        try {
            uploadRepository.deleteUploadByEnqueteId(idBackend);
        } catch (Exception e) {

        }
        try {
            pieceRepository.deletePieceByEnqueteId(idBackend);
        } catch (Exception e) {

        }
        try {
            acteurConcerneRepository.deleteActeurConcerneByEnquete(idBackend);
        } catch (Exception e) {

        }
        try {
            caracteristiqueParcelleRepository.deleteAllByEnquete_Id(idBackend);
        } catch (Exception e) {

        }
    }

    //@Transactional
    protected void deleteFromCodeParcelle(String codeParcelle) {
        Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByCodeParcelle(codeParcelle);
        Long idEnquete=null;
        if(optionalEnquete.isPresent()){
            idEnquete=optionalEnquete.get().getId();
        }
        if(idEnquete!=null) {
            System.out.println("ENQUETE ID"+idEnquete);
            try {
                uploadRepository.deleteUploadByEnqueteId(idEnquete);
            } catch (Exception e) {

            }
            try {
                pieceRepository.deletePieceByEnqueteId(idEnquete);
            } catch (Exception e) {

            }
            try {
                acteurConcerneRepository.deleteActeurConcerneByEnquete(idEnquete);
            } catch (Exception e) {

            }
            try {
                caracteristiqueParcelleRepository.deleteAllByEnquete_Id(idEnquete);
            } catch (Exception e) {

            }

            try {
                caracteristiqueBatimentRepository.deleteByEnqueteId(idEnquete);
            }catch (Exception e){

            }

            try {
                caracteristiqueUniteLogementRepository.deleteByEnqueteId(idEnquete);
            }catch (Exception e){

            }

            try {
                enqueteBatimentRepository.deleteAllByEnquete_Id(idEnquete);
            }catch (Exception e){

            }

            try {
                enqueteUniteLogementRepository.deleteAllByEnquete_id(idEnquete);
            }catch (Exception e){

            }

            try {
                uniteLogementRepository.deleteByEnqueteId(idEnquete);
            }catch (Exception e){

            }

            try {
                batimentRepository.deleteByEnqueteId(idEnquete);
            }catch (Exception e){

            }

            try {
                System.out.println("SUPPRESSION DE ENQUETE "+idEnquete);
                enqueteRepository.deleteById(idEnquete);
            }catch (Exception e){

            }
        }
    }

    private Enquete getEnqueteFromEnquetePayLoad(Enquete enquete, EnquetePayLoad enquetePayLoad) {

        if (enquetePayLoad.getUserId() != null) {
            Optional<User> optionalUser = userRepository.findById(enquetePayLoad.getUserId());
            enquete.setUser(optionalUser.orElse(null));
        }
        if (enquetePayLoad.getZoneRfuId() != null) {
            Optional<ZoneRfu> optionalZoneRfu = zoneRfuRepository.findById(enquetePayLoad.getZoneRfuId());
            enquete.setZoneRfu(optionalZoneRfu.orElse(null));
        }

        if (enquetePayLoad.getParcelleId() != null) {
            Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByNupProvisoire(enquetePayLoad.getCodeParcelle());
            //Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByExternalKeyAndTerminal_Id(enquetePayLoad.getParcelleId(), enquetePayLoad.getTerminalId());
            enquete.setParcelle(optionalParcelle.orElse(null));
        }
        if (enquetePayLoad.getBlocId() != null) {
            Optional<Bloc> optionalBloc = blocRepository.findById(enquetePayLoad.getBlocId());
            enquete.setBloc(optionalBloc.orElse(null));
        }

        if (enquetePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(enquetePayLoad.getTerminalId());
            enquete.setTerminal(optionalTpe.orElse(null));
        }
        enquete.setParcelleExternalKey(enquetePayLoad.getParcelleId());
        enquete.setStatusEnquete(enquetePayLoad.getStatusEnquete());
        enquete.setLitige(enquetePayLoad.isLitige());
        enquete.setObservationParticuliere(enquetePayLoad.getObservationParticuliere());
        enquete.setDateEnquete(enquetePayLoad.getDateEnquete());
        enquete.setDateFinalisation(enquetePayLoad.getDateFinalisation());
        enquete.setExternalKey(enquetePayLoad.getExternalKey());
        enquete.setQuartierId(enquetePayLoad.getQuartierId());
        enquete.setArrondissementId(enquetePayLoad.getArrondissementId());
        enquete.setCommuneId(enquetePayLoad.getCommuneId());
        enquete.setCommuneId(enquetePayLoad.getCommuneId());
        enquete.setDepartementId(enquetePayLoad.getDepartementId());
        enquete.setNumeroProvisoir(enquetePayLoad.getNumeroProvisoir());
        enquete.setCodeParcelle(enquetePayLoad.getCodeParcelle());
        enquete.setNomProprietaireParcelle(enquetePayLoad.getNomProprietaireParcelle());
        enquete.setCodeEquipe(enquetePayLoad.getCodeEquipe());
        enquete.setNumeroTitreFoncier(enquetePayLoad.getNumeroTitreFoncier());
        // Liste des champs pour FISCAD
        enquete.setNumEnterParcelle(enquetePayLoad.getNumEnterParcelle());
        enquete.setNumRue(enquetePayLoad.getNumRue());
        enquete.setNomRue(enquetePayLoad.getNomRue());
        enquete.setEmplacement(enquetePayLoad.getEmplacement());
        enquete.setAltitude(enquetePayLoad.getAltitude());
        enquete.setPrecision(enquetePayLoad.getPrecision());
        enquete.setNbreCoProprietaire(enquetePayLoad.getNbreCoProprietaire());
        enquete.setNbreIndivisiaire(enquetePayLoad.getNbreIndivisiaire());
        enquete.setAutreAdresse(enquetePayLoad.getAutreAdresse());
        enquete.setSurface(enquetePayLoad.getSurface());
        enquete.setNbreBatiment(enquetePayLoad.getNbreBatiment());
        enquete.setNbrePiscine(enquetePayLoad.getNbrePiscine());
        enquete.setDateDebutExcemption(enquetePayLoad.getDateDebutExcemption());
        enquete.setDateFinExcemption(enquetePayLoad.getDateFinExcemption());
        enquete.setPersonneId(enquetePayLoad.getPersonneId());
        enquete.setAutreNumeroTitreFoncier(enquete.getAutreNumeroTitreFoncier());
        return enquete;
    }


    private Batiment getBatimentFromBatimentPayLoad(Batiment batiment, BatimentPaylaod batimentPaylaod) {

        if (batimentPaylaod.getParcelleId() != null) {
            Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByExternalKeyAndTerminal_Id(batimentPaylaod.getParcelleId(), batimentPaylaod.getTerminalId());
            batiment.setParcelle(optionalParcelle.orElse(null));
        }

        if (batimentPaylaod.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(batimentPaylaod.getTerminalId());
            batiment.setTerminal(optionalTpe.orElse(null));
        }
        if (batimentPaylaod.getTerminalId() != null && batimentPaylaod.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(batimentPaylaod.getEnqueteId(),batimentPaylaod.getTerminalId());
            if(optionalEnquete.isPresent()){
                batiment.setEnqueteId(optionalEnquete.get().getId());
            }
        }
        batiment.setParcelleExternalKey(batimentPaylaod.getParcelleId());
        batiment.setEnqueteExternalKey(batimentPaylaod.getEnqueteId());
        batiment.setNub(batimentPaylaod.getNub());
        batiment.setCode(batimentPaylaod.getCode());
        batiment.setDateConstruction(batimentPaylaod.getDateConstruction());
        batiment.setExternalKey(batimentPaylaod.getExternalKey());

        return batiment;
    }

    private UniteLogement getUniteLogementFromUniteLogementPayLoad(UniteLogement uniteLogement, UniteLogementPaylaod uniteLogementPaylaod) {

        if (uniteLogementPaylaod.getBatimentId() != null) {
            Optional<Batiment> optionalBatiment = batimentRepository.findFirstByExternalKeyAndTerminal_Id(uniteLogementPaylaod.getBatimentId(), uniteLogementPaylaod.getTerminalId());
            uniteLogement.setBatiment(optionalBatiment.orElse(null));
        }

        if (uniteLogementPaylaod.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(uniteLogementPaylaod.getTerminalId());
            uniteLogement.setTerminal(optionalTpe.orElse(null));
        }
        if (uniteLogementPaylaod.getTerminalId() != null && uniteLogementPaylaod.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(uniteLogementPaylaod.getEnqueteId(),uniteLogementPaylaod.getTerminalId());
            if(optionalEnquete.isPresent()){
                uniteLogement.setEnqueteId(optionalEnquete.get().getId());
            }
        }
        uniteLogement.setEnqueteExternalKey(uniteLogementPaylaod.getEnqueteId());
        uniteLogement.setNul(uniteLogementPaylaod.getNul());
        uniteLogement.setNumeroEtage(uniteLogementPaylaod.getNumeroEtage());
        uniteLogement.setCode(uniteLogementPaylaod.getCode());
        uniteLogement.setExternalKey(uniteLogementPaylaod.getExternalKey());
        uniteLogement.setBatimentExternalKey(uniteLogementPaylaod.getBatimentId());
        return uniteLogement;

    }

    private CaracteristiqueUniteLogement getCaracteristiqueUniteLogementFromCaracteristiqueUniteLogementPayLoad(CaracteristiqueUniteLogement caracteristiqueUniteLogement, CaracteristiqueUniteLogementPaylod caracteristiqueUniteLogementPaylod) {

        if (caracteristiqueUniteLogementPaylod.getEnqueteUniteLogementId() != null) {
            Optional<EnqueteUniteLogement> optionalEnqueteUniteLogement = enqueteUniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(caracteristiqueUniteLogementPaylod.getEnqueteUniteLogementId(), caracteristiqueUniteLogementPaylod.getTerminalId());
            caracteristiqueUniteLogement.setEnqueteUniteLogement(optionalEnqueteUniteLogement.orElse(null));
        }

        if (caracteristiqueUniteLogementPaylod.getCaracteristiqueId() != null) {
            Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueUniteLogementPaylod.getCaracteristiqueId());
            caracteristiqueUniteLogement.setCaracteristique(optionalCaracteristique.orElse(null));
        }

        if (caracteristiqueUniteLogementPaylod.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueUniteLogementPaylod.getTerminalId());
            caracteristiqueUniteLogement.setTerminal(optionalTpe.orElse(null));
        }
        if (caracteristiqueUniteLogementPaylod.getTerminalId() != null && caracteristiqueUniteLogementPaylod.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(caracteristiqueUniteLogementPaylod.getEnqueteId(),caracteristiqueUniteLogementPaylod.getTerminalId());
            if(optionalEnquete.isPresent()){
                caracteristiqueUniteLogement.setEnqueteId(optionalEnquete.get().getId());
            }
        }
        caracteristiqueUniteLogement.setEnqueteExternalKey(caracteristiqueUniteLogementPaylod.getEnqueteId());
        caracteristiqueUniteLogement.setEnqueteUniteLogementExternalKey(caracteristiqueUniteLogementPaylod.getEnqueteUniteLogementId());
        caracteristiqueUniteLogement.setValeur(caracteristiqueUniteLogementPaylod.getValeur());
        caracteristiqueUniteLogement.setExternalKey(caracteristiqueUniteLogementPaylod.getExternalKey());
        return caracteristiqueUniteLogement;

    }


    private CaracteristiqueBatiment getCaracteristiqueBatimentFromCaracteristiqueBatimentPayLoad(CaracteristiqueBatiment caracteristiqueBatiment, CaracteristiqueBatimentPaylod caracteristiqueBatimentPaylod) {


        if (caracteristiqueBatimentPaylod.getEnqueteBatimentId() != null) {
            Optional<EnqueteBatiment> optionalEnqueteBatiment = enqueteBatimentRepository.findFirstByExternalKeyAndTerminal_Id(caracteristiqueBatimentPaylod.getEnqueteBatimentId(), caracteristiqueBatimentPaylod.getTerminalId());
            caracteristiqueBatiment.setEnqueteBatiment(optionalEnqueteBatiment.orElse(null));
        }

        if (caracteristiqueBatimentPaylod.getCaracteristiqueId() != null) {
            Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueBatimentPaylod.getCaracteristiqueId());
            caracteristiqueBatiment.setCaracteristique(optionalCaracteristique.orElse(null));
        }

        if (caracteristiqueBatimentPaylod.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueBatimentPaylod.getTerminalId());
            caracteristiqueBatiment.setTerminal(optionalTpe.orElse(null));
        }


        if (caracteristiqueBatimentPaylod.getTerminalId() != null && caracteristiqueBatimentPaylod.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(caracteristiqueBatimentPaylod.getEnqueteId(),caracteristiqueBatimentPaylod.getTerminalId());
            if(optionalEnquete.isPresent()){
                caracteristiqueBatiment.setEnqueteId(optionalEnquete.get().getId());
            }
        }
        caracteristiqueBatiment.setEnqueteBatimentExternalKey(caracteristiqueBatimentPaylod.getEnqueteBatimentId());
        caracteristiqueBatiment.setEnqueteExternalKey(caracteristiqueBatimentPaylod.getEnqueteId());
        caracteristiqueBatiment.setValeur(caracteristiqueBatimentPaylod.getValeur());
        caracteristiqueBatiment.setExternalKey(caracteristiqueBatimentPaylod.getExternalKey());
        return caracteristiqueBatiment;

    }

    private CaracteristiqueParcelle getCaracteristiqueParcelleFromCaracteristiqueParcellePayLoad(CaracteristiqueParcelle caracteristiqueParcelle, CaracteristiqueParcellePaylod caracteristiqueParcellePaylod) {

        if (caracteristiqueParcellePaylod.getEnqueteId() != null) {
            Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(caracteristiqueParcellePaylod.getEnqueteId(), caracteristiqueParcellePaylod.getTerminalId());

            caracteristiqueParcelle.setEnquete(optionalEnquete.orElse(null));
        }

        if (caracteristiqueParcellePaylod.getCaracteristiqueId() != null) {
            Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueParcellePaylod.getCaracteristiqueId());
            caracteristiqueParcelle.setCaracteristique(optionalCaracteristique.orElse(null));
        }

        if (caracteristiqueParcellePaylod.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueParcellePaylod.getTerminalId());
            caracteristiqueParcelle.setTerminal(optionalTpe.orElse(null));
        }

        caracteristiqueParcelle.setEnqueteExternalKey(caracteristiqueParcellePaylod.getEnqueteId());
        caracteristiqueParcelle.setValeur(caracteristiqueParcellePaylod.getValeur());
        caracteristiqueParcelle.setExternalKey(caracteristiqueParcellePaylod.getExternalKey());
        return caracteristiqueParcelle;

    }

    @Override
    public List<SyncResponse> syncParcelle(List<ParcellePayLoad> parcellePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (parcellePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune parcelle à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }

        parcellePayLoads.forEach(parcellePayLoad -> {
            System.out.println(parcellePayLoad);
            try {
                if (parcellePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(parcellePayLoad.getIdBackend(),
                            parcellePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(parcellePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(parcellePayLoad.getIdBackend(),
                                parcellePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                Parcelle parcelle = new Parcelle();
                parcellePayLoad.setSynchronise(true);
                if (parcellePayLoad.getNupProvisoire() == null || parcellePayLoad.getNupProvisoire()=="" ) {
                        parcellePayLoad.setObservation("Le code parcelle n'est pas précisé");
                        parcellePayLoad.setSynchronise(false);
                } else {
                    Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByNupProvisoire(parcellePayLoad.getNupProvisoire());
                    if(optionalParcelle.isPresent()){
                     parcelle=optionalParcelle.get();
                    }
                    parcelle = getParcelleFromParcellePayLoad(parcelle, parcellePayLoad);
                    parcelle = parcelleRepository.save(parcelle);
                    parcellePayLoad.setIdBackend(parcelle.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(parcellePayLoad.getObservation());
                syncResponse.setExternalKey(parcellePayLoad.getExternalKey());
                syncResponse.setSynchronise(parcellePayLoad.isSynchronise());
                syncResponse.setIdBackend(parcellePayLoad.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(parcellePayLoad.getIdBackend(),
                        parcellePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }


    private Parcelle getParcelleFromParcellePayLoad(Parcelle parcelle, ParcellePayLoad parcellePayLoad) {
//        if (parcellePayLoad.getSituationGeographiqueId() != null) {
//            Optional<SituationGeographique> optionalSituationGeographique = situationGeographiqueRepository.findById(parcellePayLoad.getSituationGeographiqueId());
//            parcelle.setSituationGeographique(optionalSituationGeographique.orElse(null));
//        }
        if (parcellePayLoad.getNatureDomaineId() != null) {
            Optional<NatureDomaine> optionalNatureDomaine = natureDomaineRepository.findById(parcellePayLoad.getNatureDomaineId());
            parcelle.setNatureDomaine(optionalNatureDomaine.orElse(null));
        }
        if (parcellePayLoad.getQuartierId() != null) {
            Optional<Quartier> optionalQuartier = quartierRepository.findById(parcellePayLoad.getQuartierId());
            parcelle.setQuartier(optionalQuartier.orElse(null));
        }
        if (parcellePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(parcellePayLoad.getTerminalId());
            parcelle.setTerminal(optionalTpe.orElse(null));
        }
        parcelle.setExternalKey(parcellePayLoad.getExternalKey());
        parcelle.setNupProvisoire(parcellePayLoad.getNupProvisoire());
        parcelle.setQ(parcellePayLoad.getQ());
        parcelle.setI(parcellePayLoad.getI());
        parcelle.setP(parcellePayLoad.getP());
        parcelle.setNup(parcellePayLoad.getNup());
        parcelle.setLongitude(parcellePayLoad.getLongitude());
        parcelle.setLatitude(parcellePayLoad.getLatitude());
        parcelle.setNumTitreFoncier(parcellePayLoad.getNumTitreFoncier());
        parcelle.setTypeDomaineId(parcellePayLoad.getTypeDomaineId());
        parcelle.setNumeroProvisoire(parcellePayLoad.getNumeroProvisoire());
        parcelle.setBlocId(parcellePayLoad.getBlocId());
        parcelle.setObservation(parcellePayLoad.getObservation());
        parcelle.setSituationGeographique(parcellePayLoad.getSituationGeographique());
        parcelle.setAutreNumeroTitreFoncier(parcellePayLoad.getAutreNumeroTitreFoncier());
        return parcelle;
    }


    @Override
    public List<SyncResponse> syncPiece(List<PiecePayLoad> piecePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (piecePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune pièce à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        piecePayLoads.forEach(piecePayLoad -> {
            try {
                if (piecePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                            piecePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(piecePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                                piecePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (piecePayLoad.getPersonneId() == null && piecePayLoad.getActeurConcerneId() == null) {
                            SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                            piecePayLoad.getExternalKey(), false, "La personne ou l'acteur concerné n'est pas précisé");
                            syncResponses.add(syncResponse);
                    return;
                } else {
                    if (piecePayLoad.getPersonneId() != null) {
                        Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getPersonneId(), piecePayLoad.getTerminalId());
                        if (optionalPersonne.isEmpty()) {
                            SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                                    piecePayLoad.getExternalKey(), false, "La personne précisée n'existe pas");
                            syncResponses.add(syncResponse);
                            return;
                        }
                    }
                    if (piecePayLoad.getActeurConcerneId() != null) {
                        Optional<ActeurConcerne> optionalActeurConcerne = acteurConcerneRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getActeurConcerneId(), piecePayLoad.getTerminalId());
                        if (optionalActeurConcerne.isEmpty()) {
                            SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                                    piecePayLoad.getExternalKey(), false, "L'acteur concerné précisé n'existe pas");
                            syncResponses.add(syncResponse);
                            return;
                        }
                    }
                }
                Piece piece = new Piece();
                piecePayLoad.setSynchronise(true);
                System.out.println("JE SUIS AU DEBUT DU TEST DE PIECE");
                System.out.println(piecePayLoad);
                Optional<Piece> optionalPiece=Optional.empty();
                if (piecePayLoad.getIdBackend() != null && piecePayLoad.getIdBackend() != 0) {
                    optionalPiece = pieceRepository.findById(piecePayLoad.getIdBackend());
                }else{
                    optionalPiece = pieceRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getExternalKey(),piecePayLoad.getTerminalId());
                }
                if (optionalPiece.isPresent()) {
                    piece = optionalPiece.get();
                }else {
                    piecePayLoad.setIdBackend(null);
                }

                piece = getPieceFromPiecePayLoad(piece, piecePayLoad);
                piece = pieceRepository.save(piece);
                piecePayLoad.setIdBackend(piece.getId());

                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(piecePayLoad.getObservation());
                syncResponse.setExternalKey(piecePayLoad.getExternalKey());
                syncResponse.setSynchronise(piecePayLoad.isSynchronise());
                syncResponse.setIdBackend(piecePayLoad.getIdBackend());
                syncResponses.add(syncResponse);

                try{
                    PieceMetaData pieceMetaData= new PieceMetaData();
                    pieceMetaData.setPieceJson(piece);
                    pieceMetaData.setPieceId(piece.getId());
                    pieceMetaDataRepository.save(pieceMetaData);
                }catch (Exception e){
                    e.printStackTrace();
                }

            } catch (Exception e) {
                SyncResponse syncResponse = new SyncResponse(piecePayLoad.getIdBackend(),
                        piecePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }


    private Piece getPieceFromPiecePayLoad(Piece piece, PiecePayLoad piecePayLoad) {
        if (piecePayLoad.getTypePieceId() != null) {
            Optional<TypePiece> optionalTypePiece = typePieceRepository.findById(piecePayLoad.getTypePieceId());
            piece.setTypePiece(optionalTypePiece.orElse(null));
        } else {
            piece.setTypePiece(null);
        }
        if (piecePayLoad.getPersonneId() != null) {
            Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getPersonneId(), piecePayLoad.getTerminalId());
            piece.setPersonne(optionalPersonne.orElse(null));
        } else {
            piece.setPersonne(null);
        }
        if (piecePayLoad.getActeurConcerneId() != null) {
            Optional<ActeurConcerne> optionalActeurConcerne = acteurConcerneRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getActeurConcerneId(), piecePayLoad.getTerminalId());
            piece.setActeurConcerne(optionalActeurConcerne.orElse(null));
        } else {
            piece.setActeurConcerne(null);
        }
        if (piecePayLoad.getModeAcquisitionId() != null) {
            Optional<ModeAcquisition> optionalModeAcquisition = modeAcquisitionRepository.findById(piecePayLoad.getModeAcquisitionId());
            piece.setModeAcquisition(optionalModeAcquisition.orElse(null));
        } else {
            piece.setModeAcquisition(null);
        }
        if (piecePayLoad.getSourceDroitId() != null) {
            Optional<SourceDroit> optionalSourceDroit = sourceDroitRepository.findById(piecePayLoad.getSourceDroitId());
            piece.setSourceDroit(optionalSourceDroit.orElse(null));
        } else {
            piece.setSourceDroit(null);
        }
        if (piecePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(piecePayLoad.getTerminalId());
            piece.setTerminal(optionalTpe.orElse(null));
        }

        if (piecePayLoad.getTerminalId() != null && piecePayLoad.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(piecePayLoad.getEnqueteId(),piecePayLoad.getTerminalId());
            if(optionalEnquete.isPresent()){
                piece.setEnqueteId(optionalEnquete.get().getId());
            }
        }

        piece.setActeurConcerneExternalKey(piecePayLoad.getActeurConcerneId());
        piece.setPersonneExternalKey(piecePayLoad.getPersonneId());
        piece.setEnqueteExternalKey(piecePayLoad.getEnqueteId());
        piece.setNumeroPiece(piecePayLoad.getNumeroPiece());
        piece.setUrl(piecePayLoad.getUrl());
        piece.setExternalKey(piecePayLoad.getExternalKey());
        piece.setDateExpiration(piecePayLoad.getDateExpiration());
        piece.setMax_numero_piece_id(piecePayLoad.getMax_numero_piece_id());
        piece.setMax_numero_acteur_concerne_id(piecePayLoad.getMax_numero_acteur_concerne_id());
        piece.setEnqueteId(piecePayLoad.getEnqueteId());
        piece.setBlocId(piecePayLoad.getBlocId());
        piece.setEnqueteExternalKey(piecePayLoad.getEnqueteId());
        return piece;
    }

    @Override
    public List<SyncResponse> syncActeurConcerne(List<ActeurConcernePayLoad> acteurConcernePayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (acteurConcernePayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucun acteur concerné à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        acteurConcernePayLoads.forEach(acteurConcernePayLoad -> {
            try {
                if (acteurConcernePayLoad.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                            acteurConcernePayLoad.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(acteurConcernePayLoad.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                                acteurConcernePayLoad.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (acteurConcernePayLoad.getPersonneId() == null) {
                    SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                            acteurConcernePayLoad.getExternalKey(), false, "La personne n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(acteurConcernePayLoad.getPersonneId(), acteurConcernePayLoad.getTerminalId());
                    if (optionalPersonne.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                                acteurConcernePayLoad.getExternalKey(), false, "La personne précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (acteurConcernePayLoad.getEnqueteId() == null) {
                    SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                            acteurConcernePayLoad.getExternalKey(), false, "L'enquête n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(acteurConcernePayLoad.getEnqueteId(), acteurConcernePayLoad.getTerminalId());
                    if (optionalEnquete.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                                acteurConcernePayLoad.getExternalKey(), false, "L'enquête précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                ActeurConcerne acteurConcerne = new ActeurConcerne();
                acteurConcernePayLoad.setSynchronise(true);
                if (acteurConcernePayLoad.getIdBackend() != null && acteurConcernePayLoad.getIdBackend() != 0) {
                    Optional<ActeurConcerne> optionalActeurConcerne = acteurConcerneRepository.findById(acteurConcernePayLoad.getIdBackend());
                    if (optionalActeurConcerne.isPresent()) {
                        acteurConcerne = optionalActeurConcerne.get();
                    } else {
                        acteurConcernePayLoad.setIdBackend(null);
                    }
                    acteurConcerne = getActeurConcerneFromActeurConcernePayLoad(acteurConcerne, acteurConcernePayLoad);
                    acteurConcerne = acteurConcerneRepository.save(acteurConcerne);
                    acteurConcernePayLoad.setIdBackend(acteurConcerne.getId());

                } else {
                    Optional<ActeurConcerne> optionalActeurConcerne = acteurConcerneRepository.findFirstByExternalKeyAndTerminal_Id(acteurConcernePayLoad.getExternalKey(),acteurConcernePayLoad.getTerminalId());
                    if(optionalActeurConcerne.isPresent()){
                        acteurConcerne=optionalActeurConcerne.get();
                    }
                    acteurConcerne = getActeurConcerneFromActeurConcernePayLoad(acteurConcerne, acteurConcernePayLoad);
                    acteurConcerne = acteurConcerneRepository.save(acteurConcerne);
                    acteurConcernePayLoad.setIdBackend(acteurConcerne.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(acteurConcernePayLoad.getObservation());
                syncResponse.setExternalKey(acteurConcernePayLoad.getExternalKey());
                syncResponse.setSynchronise(acteurConcernePayLoad.isSynchronise());
                syncResponse.setIdBackend(acteurConcernePayLoad.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(acteurConcernePayLoad.getIdBackend(),
                        acteurConcernePayLoad.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }


    private ActeurConcerne getActeurConcerneFromActeurConcernePayLoad(ActeurConcerne acteurConcerne, ActeurConcernePayLoad acteurConcernePayLoad) {

        if (acteurConcernePayLoad.getEnqueteId() != null) {
            Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(acteurConcernePayLoad.getEnqueteId(), acteurConcernePayLoad.getTerminalId());
            acteurConcerne.setEnquete(optionalEnquete.orElse(null));
        }
        if (acteurConcernePayLoad.getEnqueteId() != null) {
            Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(acteurConcernePayLoad.getPersonneId(), acteurConcernePayLoad.getTerminalId());
            acteurConcerne.setPersonne(optionalPersonne.orElse(null));
        }
        if (acteurConcernePayLoad.getPositionRepresentationId() != null) {
            Optional<PositionRepresentation> optionalPositionRepresentation = positionRepresentationRepository.findById(acteurConcernePayLoad.getPositionRepresentationId());
            acteurConcerne.setPositionRepresentation(optionalPositionRepresentation.orElse(null));
        }
        if (acteurConcernePayLoad.getTypeContestationId() != null) {
            Optional<TypeContestation> optionalTypeContestation = typeContestationRepository.findById(acteurConcernePayLoad.getTypeContestationId());
            acteurConcerne.setTypeContestation(optionalTypeContestation.orElse(null));
        }
        if (acteurConcernePayLoad.getTypeRepresentationId() != null) {
            Optional<TypeRepresentation> optionalTypeRepresentation = typeRepresentationRepository.findById(acteurConcernePayLoad.getTypeRepresentationId());
            acteurConcerne.setTypeRepresentation(optionalTypeRepresentation.orElse(null));
        }
        if (acteurConcernePayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(acteurConcernePayLoad.getTerminalId());
            acteurConcerne.setTerminal(optionalTpe.orElse(null));
        }

        acteurConcerne.setEnqueteExternalKey(acteurConcernePayLoad.getEnqueteId());
        acteurConcerne.setPersonneExternalKey(acteurConcernePayLoad.getPersonneId());
        acteurConcerne.setPart(acteurConcernePayLoad.getPart());
        acteurConcerne.setTypeDroit(acteurConcernePayLoad.getTypeDroit());
        acteurConcerne.setExternalKey(acteurConcernePayLoad.getExternalKey());
        acteurConcerne.setRoleActeur(acteurConcernePayLoad.getRoleActeur());
        acteurConcerne.setBlocId(acteurConcernePayLoad.getBlocId());
        acteurConcerne.setHaveDeclarant(acteurConcernePayLoad.getHaveDeclarant());
        acteurConcerne.setMax_numero_acteur_concerne_id(acteurConcernePayLoad.getMax_numero_acteur_concerne_id());
        return acteurConcerne;
    }

    @Override
    public SyncResponse syncFiles(MultipartFile file,
                                  Long idBackend,
                                  Long externalKey,
                                  Long pieceId,
                                  Long membreGroupeId,
                                  Long terminalId,
                                  String name,
                                  String filePath,
                                  Long max_numero_piece_id,
                                  Long max_numero_upload_id,
                                  Long max_numero_acteur_concerne_id,
                                  Long enqueteId,
                                  Long enqueteBatimentId,
                                  Long enqueteUniteLogementId,
                                  Long personneId) {

        UploadPayLoad uploadPayLoad = new UploadPayLoad();
        uploadPayLoad.setSynchronise(false);
        uploadPayLoad.setFile(file);
        uploadPayLoad.setExternalKey(externalKey);
        uploadPayLoad.setPieceId(pieceId);
        uploadPayLoad.setIdBackend(idBackend);
        uploadPayLoad.setMembreGroupeId(membreGroupeId);
        uploadPayLoad.setTerminalId(terminalId);
        uploadPayLoad.setName(name);
        uploadPayLoad.setFilePath(filePath);
        uploadPayLoad.setMax_numero_upload_id(max_numero_upload_id);
        uploadPayLoad.setMax_numero_piece_id(max_numero_piece_id);
        uploadPayLoad.setMax_numero_acteur_concerne_id(max_numero_acteur_concerne_id);
        uploadPayLoad.setEnqueteId(enqueteId);
        uploadPayLoad.setEnqueteBatimentId(enqueteBatimentId);
        uploadPayLoad.setEnqueteUniteLogementId(enqueteUniteLogementId);
        uploadPayLoad.setPersonneId(personneId);
        System.out.println("ZZZ");
        System.out.println(uploadPayLoad);
        try {
            Upload upload = new Upload();
            SyncResponse syncResponse = new SyncResponse();
            if (terminalId == null) {
                syncResponse = new SyncResponse(idBackend,
                        externalKey, false, "Le terminal n'est pas précisé");
                return syncResponse;
            } else {
                Optional<Tpe> optionalTpe = tpeRepository.findById(terminalId);
                if (optionalTpe.isEmpty()) {
                    syncResponse = new SyncResponse(idBackend,
                            externalKey, false, "Le terminal n'existe pas");
                    return syncResponse;
                }
            }

            if ((uploadPayLoad.getPieceId() == null || uploadPayLoad.getPieceId() == 0)
                    && (uploadPayLoad.getMembreGroupeId() == null || uploadPayLoad.getMembreGroupeId() == 0)
                    && (uploadPayLoad.getPersonneId() == null || uploadPayLoad.getPersonneId() == 0)
                    && (uploadPayLoad.getEnqueteBatimentId() == null || uploadPayLoad.getEnqueteBatimentId() == 0)
                    && (uploadPayLoad.getEnqueteUniteLogementId() == null || uploadPayLoad.getEnqueteUniteLogementId() == 0)) {

                    syncResponse = new SyncResponse(uploadPayLoad.getIdBackend(),
                            uploadPayLoad.getExternalKey(), false, "La pièce ou le membre groupe concernée ou l'enquête batiment ou l'enquête unité de logement ou la personnes n'est pas précisé");
                    return syncResponse;
            } else {
                Optional<EnqueteUniteLogement> optionalEnqueteUniteLogement = null;
                if (uploadPayLoad.getEnqueteUniteLogementId() != null && uploadPayLoad.getEnqueteUniteLogementId() != 0) {
                    optionalEnqueteUniteLogement = enqueteUniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getEnqueteUniteLogementId(), uploadPayLoad.getTerminalId());
                }

                Optional<EnqueteBatiment> optionalEnqueteBatiment = null;
                if (uploadPayLoad.getEnqueteBatimentId() != null && uploadPayLoad.getEnqueteBatimentId() != 0) {
                    optionalEnqueteBatiment = enqueteBatimentRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getEnqueteBatimentId(), uploadPayLoad.getTerminalId());
                }


                Optional<Piece> optionalPiece = null;
                if (uploadPayLoad.getPieceId() != null) {
                    optionalPiece = pieceRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getPieceId(), terminalId);
                }
                Optional<MembreGroupe> optionalMembreGroupe = null;
                if (uploadPayLoad.getMembreGroupeId() != null) {
                    optionalMembreGroupe = membreGroupeRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getMembreGroupeId(), terminalId);
                }

                Optional<Personne> optionalPersonne = null;
                if (uploadPayLoad.getPersonneId() != null) {
                    optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getPersonneId(),terminalId);
                }

                if ((optionalMembreGroupe == null || optionalMembreGroupe.isEmpty())
                        && (optionalPiece == null || optionalPiece.isEmpty())
                        && (optionalPersonne==null || optionalPersonne.isEmpty())
                        && (optionalEnqueteUniteLogement == null || optionalEnqueteUniteLogement.isEmpty())
                        && (optionalEnqueteBatiment == null || optionalEnqueteBatiment.isEmpty())
                        ) {
                    syncResponse = new SyncResponse(uploadPayLoad.getIdBackend(),
                            uploadPayLoad.getExternalKey(), false, "La pièce ou le groupe ou la personne précisée n'existe ou l'enquete batiment ou l'enquete unité de logement  pas");
                    return syncResponse;
                }
            }

            uploadPayLoad.setSynchronise(true);
            if (uploadPayLoad.getIdBackend() != null && uploadPayLoad.getIdBackend() != 0) {
                Optional<Upload> optionalUpload = uploadRepository.findById(uploadPayLoad.getIdBackend());
                if (optionalUpload.isPresent()) {
                    upload = optionalUpload.get();
                }else{
                    uploadPayLoad.setIdBackend(null);
                }
                    upload = getUploadFromUplaodPayLoad(upload, uploadPayLoad);
                    uploadPayLoad.setIdBackend(upload.getId());

            } else {
                Optional<Upload> optionalUpload = uploadRepository.findDistinctFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getExternalKey(), uploadPayLoad.getTerminalId());
                if(optionalUpload.isPresent()) {
                    upload = optionalUpload.get();
                }
                upload = getUploadFromUplaodPayLoad(upload, uploadPayLoad);
                uploadPayLoad.setIdBackend(upload.getId());
            }

            if(upload.getId()!=null) {
                try {
                    UploadMetaData uploadMetaData = new UploadMetaData();
                    uploadMetaData.setUploadJson(upload);
                    uploadMetaData.setUploadId(upload.getId());
                    uploadMetaDataRepository.save(uploadMetaData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            syncResponse.setObservation(uploadPayLoad.getObservation());
            syncResponse.setExternalKey(uploadPayLoad.getExternalKey());
            syncResponse.setSynchronise(uploadPayLoad.isSynchronise());
            syncResponse.setIdBackend(uploadPayLoad.getIdBackend());
            return syncResponse;
        } catch (Exception e) {
            e.printStackTrace();
            SyncResponse syncResponse = new SyncResponse(uploadPayLoad.getIdBackend(),
                    uploadPayLoad.getExternalKey(), false, "Erreur inattendue");
            return syncResponse;
        }
    }

    @Override
    public List<SyncResponse> syncEnqueteFromMobile(List<Long> idEnquete) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (idEnquete == null) {
            return null;
        } else {
            idEnquete.forEach(aLong -> {
                Optional<Enquete> optionalEnquete = enqueteRepository.findById(aLong);
                if (optionalEnquete.isPresent()) {
                    optionalEnquete.get().setSynchronise(true);
                    Enquete enquete = enqueteRepository.save(optionalEnquete.get());
                    SyncResponse syncResponse = new SyncResponse();
                    syncResponse.setSynchronise(enquete.isSynchronise());
                    syncResponse.setExternalKey(enquete.getExternalKey());
                    syncResponse.setIdBackend(enquete.getId());
                    syncResponses.add(syncResponse);
                }
            });
            return syncResponses;
        }
    }

    public Upload getUploadFromUplaodPayLoad(Upload upload, UploadPayLoad uploadPayLoad) {
        System.out.println("YYY");
        if (uploadPayLoad.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(uploadPayLoad.getTerminalId());
            upload.setTerminal(optionalTpe.orElse(null));
        }
        if (uploadPayLoad.getPieceId() != null) {
            Optional<Piece> optionalPiece = pieceRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getPieceId(), uploadPayLoad.getTerminalId());
            upload.setPiece(optionalPiece.orElse(null));
        }
        if (uploadPayLoad.getMembreGroupeId() != null) {
            Optional<MembreGroupe> optionalMembreGroupe = membreGroupeRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getMembreGroupeId(), uploadPayLoad.getTerminalId());
            upload.setMembreGroupe(optionalMembreGroupe.orElse(null));
        }
        if(uploadPayLoad.getPersonneId() != null){
            Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getPersonneId(),uploadPayLoad.getTerminalId());
            upload.setPersonne(optionalPersonne.orElse(null));
        }
        if (uploadPayLoad.getEnqueteBatimentId() != null) {
            Optional<EnqueteBatiment> optionalEnqueteBatiment = enqueteBatimentRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getEnqueteBatimentId(), uploadPayLoad.getTerminalId());
            upload.setEnqueteBatiment(optionalEnqueteBatiment.orElse(null));
        }
        if (uploadPayLoad.getEnqueteUniteLogementId() != null) {
            Optional<EnqueteUniteLogement> optionalEnqueteUniteLogement = enqueteUniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getEnqueteUniteLogementId(), uploadPayLoad.getTerminalId());
            upload.setEnqueteUniteLogement(optionalEnqueteUniteLogement.orElse(null));
        }

        if (uploadPayLoad.getIdBackend() != null && uploadPayLoad.getIdBackend() != 0) {
            try {
                fileStorageService.deleteFile(upload.getFileName());
            } catch (IOException e) {
                e.printStackTrace();
                //throw new RuntimeException(e);
            }
        }

        if (uploadPayLoad.getTerminalId() != null && uploadPayLoad.getEnqueteId()!=null) {
            Optional<Enquete> optionalEnquete=enqueteRepository.findFirstByExternalKeyAndTerminal_Id(uploadPayLoad.getEnqueteId(),uploadPayLoad.getTerminalId());
            if(optionalEnquete.isPresent()){
                upload.setEnqueteId(optionalEnquete.get().getId());
            }
        }

        String fileName = fileStorageService.storeFile(uploadPayLoad.getFile());
        upload.setExternalKey(uploadPayLoad.getExternalKey());
        upload.setFileName(fileName);
        upload.setMimeType(uploadPayLoad.getFile().getContentType());
        upload.setSize(uploadPayLoad.getFile().getSize());
        upload.setOriginalFileName(uploadPayLoad.getFile().getOriginalFilename());
        upload.setName(uploadPayLoad.getName());
        upload.setFilePath(uploadPayLoad.getFilePath());
        upload.setMax_numero_upload_id(uploadPayLoad.getMax_numero_upload_id());
        upload.setMax_numero_piece_id(uploadPayLoad.getMax_numero_piece_id());
        upload.setMax_numero_acteur_concerne_id(uploadPayLoad.getMax_numero_acteur_concerne_id());
        upload.setEnqueteExternalKey(uploadPayLoad.getEnqueteId());
        upload.setBlocId(uploadPayLoad.getBlocId());
        upload.setEnqueteBatimentExternalKey(uploadPayLoad.getEnqueteBatimentId());
        upload.setEnqueteUniteLogementExternalKey(uploadPayLoad.getEnqueteUniteLogementId());
        upload.setPieceExternalKey(uploadPayLoad.getPieceId());
        upload.setPersonneExternalKey(uploadPayLoad.getPersonneId());
        upload = uploadRepository.save(upload);
        return upload;
    }


    @Override
    public List<SyncResponse> syncBatiment(List<BatimentPaylaod> batimentPaylaods) {

        List<SyncResponse> syncResponses = new ArrayList<>();
        if (batimentPaylaods == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucun batiment à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        batimentPaylaods.forEach(batimentPaylaod -> {
            try {
                System.out.println(batimentPaylaods);
                if (batimentPaylaod.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(batimentPaylaod.getIdBackend(),
                            batimentPaylaod.getExternalKey(), false, "Le terminal n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(batimentPaylaod.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(batimentPaylaod.getIdBackend(),
                                batimentPaylaod.getExternalKey(), false, "Le terminal n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (batimentPaylaod.getParcelleId() == null) {
                    SyncResponse syncResponse = new SyncResponse(batimentPaylaod.getIdBackend(),
                            batimentPaylaod.getExternalKey(), false, "La parcelle n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Parcelle> optionalParcelle = parcelleRepository.findFirstByExternalKeyAndTerminal_Id(batimentPaylaod.getParcelleId(), batimentPaylaod.getTerminalId());
                    if (optionalParcelle.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(batimentPaylaod.getIdBackend(),
                                batimentPaylaod.getExternalKey(), false, "La parcelle précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                Batiment batiment = new Batiment();
                batimentPaylaod.setSynchronise(true);
                if (batimentPaylaod.getIdBackend() != null && batimentPaylaod.getIdBackend() != 0) {
                    Optional<Batiment> batimentOptional = batimentRepository.findById(batimentPaylaod.getIdBackend());
                    if (batimentOptional.isPresent()) {
                        batiment = batimentOptional.get();
                    } else {
                        batimentPaylaod.setIdBackend(null);
                    }
                        batiment = getBatimentFromBatimentPayLoad(batiment, batimentPaylaod);
                        batiment = batimentRepository.save(batiment);
                        batimentPaylaod.setIdBackend(batiment.getId());

                } else {
                    Optional<Batiment> batimentOptional = batimentRepository.findFirstByExternalKeyAndTerminal_Id(batimentPaylaod.getExternalKey(),batimentPaylaod.getTerminalId());
                    if(batimentOptional.isPresent()){
                        batiment=batimentOptional.get();
                    }
                    batiment = getBatimentFromBatimentPayLoad(batiment, batimentPaylaod);
                    batimentRepository.save(batiment);
                    batimentPaylaod.setIdBackend(batiment.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(batimentPaylaod.getObservation());
                syncResponse.setExternalKey(batimentPaylaod.getExternalKey());
                syncResponse.setSynchronise(batimentPaylaod.isSynchronise());
                syncResponse.setIdBackend(batimentPaylaod.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(batimentPaylaod.getIdBackend(),
                        batimentPaylaod.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }


    @Override
    public List<SyncResponse> syncUniteLogement(List<UniteLogementPaylaod> uniteLogementPaylaods) {

        List<SyncResponse> syncResponses = new ArrayList<>();
        if (uniteLogementPaylaods == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune unité de logement à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        uniteLogementPaylaods.forEach(uniteLogementPaylaod -> {
            try {
                if (uniteLogementPaylaod.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(uniteLogementPaylaod.getIdBackend(),
                            uniteLogementPaylaod.getExternalKey(), false, "Le terminal n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(uniteLogementPaylaod.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(uniteLogementPaylaod.getIdBackend(),
                                uniteLogementPaylaod.getExternalKey(), false, "Le terminal n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (uniteLogementPaylaod.getBatimentId() == null) {
                    SyncResponse syncResponse = new SyncResponse(uniteLogementPaylaod.getIdBackend(),
                            uniteLogementPaylaod.getExternalKey(), false, "Le batiment n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Batiment> optionalBatiment = batimentRepository.findFirstByExternalKeyAndTerminal_Id(uniteLogementPaylaod.getBatimentId(), uniteLogementPaylaod.getTerminalId());
                    if (optionalBatiment.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(uniteLogementPaylaod.getIdBackend(),
                                uniteLogementPaylaod.getExternalKey(), false, "Le batiment précisé n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                UniteLogement uniteLogement = new UniteLogement();
                uniteLogementPaylaod.setSynchronise(true);
                if (uniteLogementPaylaod.getIdBackend() != null && uniteLogementPaylaod.getIdBackend() != 0) {
                    Optional<UniteLogement> uniteLogementOptional = uniteLogementRepository.findById(uniteLogementPaylaod.getIdBackend());
                    if (uniteLogementOptional.isPresent()) {
                        uniteLogement = uniteLogementOptional.get();
                    } else {
                        uniteLogementPaylaod.setIdBackend(null);
                    }
                        uniteLogement = getUniteLogementFromUniteLogementPayLoad(uniteLogement, uniteLogementPaylaod);
                        uniteLogementRepository.save(uniteLogement);
                        uniteLogementPaylaod.setIdBackend(uniteLogement.getId());

                } else {
                    Optional<UniteLogement> uniteLogementOptional = uniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(uniteLogementPaylaod.getExternalKey(),uniteLogementPaylaod.getTerminalId());
                    if(uniteLogementOptional.isPresent()){
                        uniteLogement=uniteLogementOptional.get();
                    }
                    uniteLogement = getUniteLogementFromUniteLogementPayLoad(uniteLogement, uniteLogementPaylaod);
                    uniteLogementRepository.save(uniteLogement);
                    uniteLogementPaylaod.setIdBackend(uniteLogement.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(uniteLogementPaylaod.getObservation());
                syncResponse.setExternalKey(uniteLogementPaylaod.getExternalKey());
                syncResponse.setSynchronise(uniteLogementPaylaod.isSynchronise());
                syncResponse.setIdBackend(uniteLogementPaylaod.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(uniteLogementPaylaod.getIdBackend(),
                        uniteLogementPaylaod.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    @Override
    public List<SyncResponse> syncCaracteristiqueBatiment(List<CaracteristiqueBatimentPaylod> caracteristiqueBatimentPaylods) {
        System.out.println("DANS CARACT BATIMENT");
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (caracteristiqueBatimentPaylods == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune caracteristique de bâtiment à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        caracteristiqueBatimentPaylods.forEach(caracteristiqueBatimentPaylod -> {
            try {
                System.out.println(caracteristiqueBatimentPaylod);
                if (caracteristiqueBatimentPaylod.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueBatimentPaylod.getIdBackend(),
                            caracteristiqueBatimentPaylod.getExternalKey(), false, "Le terminal n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueBatimentPaylod.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueBatimentPaylod.getIdBackend(),
                                caracteristiqueBatimentPaylod.getExternalKey(), false, "Le terminal n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (caracteristiqueBatimentPaylod.getCaracteristiqueId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueBatimentPaylod.getIdBackend(),
                            caracteristiqueBatimentPaylod.getExternalKey(), false, "La caracteristique du batiment n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueBatimentPaylod.getCaracteristiqueId());
                    if (optionalCaracteristique.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueBatimentPaylod.getIdBackend(),
                                caracteristiqueBatimentPaylod.getExternalKey(), false, "La caracteristique du batiment précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                CaracteristiqueBatiment caracteristiqueBatiment = new CaracteristiqueBatiment();
                caracteristiqueBatimentPaylod.setSynchronise(true);
                caracteristiqueBatiment = getCaracteristiqueBatimentFromCaracteristiqueBatimentPayLoad(caracteristiqueBatiment, caracteristiqueBatimentPaylod);
                caracteristiqueBatimentRepository.save(caracteristiqueBatiment);
                caracteristiqueBatimentPaylod.setIdBackend(caracteristiqueBatiment.getId());

                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(caracteristiqueBatimentPaylod.getObservation());
                syncResponse.setExternalKey(caracteristiqueBatimentPaylod.getExternalKey());
                syncResponse.setSynchronise(caracteristiqueBatimentPaylod.isSynchronise());
                syncResponse.setIdBackend(caracteristiqueBatimentPaylod.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(caracteristiqueBatimentPaylod.getIdBackend(),
                        caracteristiqueBatimentPaylod.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    private void deleteAllCaracteristiqueBatimentFromEnqueteBatiment(EnqueteBatiment enqueteBatiment) {
        caracteristiqueBatimentRepository.deleteAllByEnqueteBatiment(enqueteBatiment);
    }


    @Override
    public List<SyncResponse> syncCaracteristiqueUniteLogement(List<CaracteristiqueUniteLogementPaylod> caracteristiqueUniteLogementPaylods) {

        List<SyncResponse> syncResponses = new ArrayList<>();
        if (caracteristiqueUniteLogementPaylods == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune caracteristique d'unité de logement à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        caracteristiqueUniteLogementPaylods.forEach(caracteristiqueUniteLogementPaylod -> {
            try {
                if (caracteristiqueUniteLogementPaylod.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueUniteLogementPaylod.getIdBackend(),
                            caracteristiqueUniteLogementPaylod.getExternalKey(), false, "Le terminal n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueUniteLogementPaylod.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueUniteLogementPaylod.getIdBackend(),
                                caracteristiqueUniteLogementPaylod.getExternalKey(), false, "Le terminal n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (caracteristiqueUniteLogementPaylod.getCaracteristiqueId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueUniteLogementPaylod.getIdBackend(),
                            caracteristiqueUniteLogementPaylod.getExternalKey(), false, "La caracteristique de l'unité de logement n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueUniteLogementPaylod.getCaracteristiqueId());
                    if (optionalCaracteristique.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueUniteLogementPaylod.getIdBackend(),
                                caracteristiqueUniteLogementPaylod.getExternalKey(), false, "La caracteristique de l'unité de logement précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                CaracteristiqueUniteLogement caracteristiqueUniteLogement = new CaracteristiqueUniteLogement();
                caracteristiqueUniteLogementPaylod.setSynchronise(true);
                caracteristiqueUniteLogement = getCaracteristiqueUniteLogementFromCaracteristiqueUniteLogementPayLoad(caracteristiqueUniteLogement, caracteristiqueUniteLogementPaylod);
                caracteristiqueUniteLogementRepository.save(caracteristiqueUniteLogement);
                caracteristiqueUniteLogementPaylod.setIdBackend(caracteristiqueUniteLogement.getId());
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(caracteristiqueUniteLogementPaylod.getObservation());
                syncResponse.setExternalKey(caracteristiqueUniteLogementPaylod.getExternalKey());
                syncResponse.setSynchronise(caracteristiqueUniteLogementPaylod.isSynchronise());
                syncResponse.setIdBackend(caracteristiqueUniteLogementPaylod.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(caracteristiqueUniteLogementPaylod.getIdBackend(),
                        caracteristiqueUniteLogementPaylod.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }

    private void deleteAllCaracteristiqueUniteLogementFromEnqueteUniteLogement(EnqueteUniteLogement enqueteUniteLogement) {
        caracteristiqueUniteLogementRepository.deleteAllByEnqueteUniteLogement(enqueteUniteLogement);
    }


    @Override
    public List<SyncResponse> syncCaracteristiqueParcelle(List<CaracteristiqueParcellePaylod> caracteristiqueParcellePaylods) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (caracteristiqueParcellePaylods == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune caracteristique de parcelle à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        caracteristiqueParcellePaylods.forEach(caracteristiqueParcellePaylod -> {
            try {
                if (caracteristiqueParcellePaylod.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueParcellePaylod.getIdBackend(),
                            caracteristiqueParcellePaylod.getExternalKey(), false, "Le terminal n'est pas précisé.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(caracteristiqueParcellePaylod.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueParcellePaylod.getIdBackend(),
                                caracteristiqueParcellePaylod.getExternalKey(), false, "Le terminal n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (caracteristiqueParcellePaylod.getCaracteristiqueId() == null) {
                    SyncResponse syncResponse = new SyncResponse(caracteristiqueParcellePaylod.getIdBackend(),
                            caracteristiqueParcellePaylod.getExternalKey(), false, "La caracteristique de la parcelle n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Caracteristique> optionalCaracteristique = caracteristiqueRepository.findById(caracteristiqueParcellePaylod.getCaracteristiqueId());
                    if (optionalCaracteristique.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(caracteristiqueParcellePaylod.getIdBackend(),
                                caracteristiqueParcellePaylod.getExternalKey(), false, "La caracteristique de la parcelle précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                CaracteristiqueParcelle caracteristiqueParcelle = new CaracteristiqueParcelle();
                caracteristiqueParcellePaylod.setSynchronise(true);
                caracteristiqueParcelle = getCaracteristiqueParcelleFromCaracteristiqueParcellePayLoad(caracteristiqueParcelle, caracteristiqueParcellePaylod);
                caracteristiqueParcelleRepository.save(caracteristiqueParcelle);
                caracteristiqueParcellePaylod.setIdBackend(caracteristiqueParcelle.getId());

                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(caracteristiqueParcellePaylod.getObservation());
                syncResponse.setExternalKey(caracteristiqueParcellePaylod.getExternalKey());
                syncResponse.setSynchronise(caracteristiqueParcellePaylod.isSynchronise());
                syncResponse.setIdBackend(caracteristiqueParcellePaylod.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(caracteristiqueParcellePaylod.getIdBackend(),
                        caracteristiqueParcellePaylod.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });
        return syncResponses;
    }

    private void deleteAllCaracteristiqueParcelleFromEnquete(Enquete enquete) {
        caracteristiqueParcelleRepository.deleteAllByEnquete(enquete);
    }


    @Override
    public List<SyncResponse> syncEnqueteBatiment(List<EnqueteBatimentPayload> enqueteBatimentPayLoads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (enqueteBatimentPayLoads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune enquête de batiment à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        enqueteBatimentPayLoads.forEach(enqueteBatimentPayload -> {
            System.out.println(enqueteBatimentPayload);
            try {
                System.out.println(enqueteBatimentPayload);
                if (enqueteBatimentPayload.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                            enqueteBatimentPayload.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    System.out.println("PAS DE TPE");
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(enqueteBatimentPayload.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                                enqueteBatimentPayload.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        System.out.println("PAS DE TPE");
                        return;
                    }
                }

                if (enqueteBatimentPayload.getUserId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                            enqueteBatimentPayload.getExternalKey(), false, "L'enquêteur n'est pas précisé");
                    syncResponses.add(syncResponse);
                    System.out.println("PAS DE USER");
                    return;
                } else {
                    Optional<User> optionalUser = userRepository.findById(enqueteBatimentPayload.getUserId());
                    if (optionalUser.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                                enqueteBatimentPayload.getExternalKey(), false, "L'enquêteur précisé n'existe pas");
                        syncResponses.add(syncResponse);
                        System.out.println("PAS DE USER");
                        return;
                    }
                }
                if (enqueteBatimentPayload.getEnqueteId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                            enqueteBatimentPayload.getExternalKey(), false, "L'enquete de la parcelle n'est pas précisée");
                    syncResponses.add(syncResponse);
                    System.out.println("PAS DE ENQUETE");
                    return;
                } else {
                    Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getEnqueteId(), enqueteBatimentPayload.getTerminalId());
                    if (optionalEnquete.isEmpty()) {
                        System.out.println("PAS DE ENQUETE");
                        SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                                enqueteBatimentPayload.getExternalKey(), false, "L'enquete de la parcelle précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enqueteBatimentPayload.getPersonneId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                            enqueteBatimentPayload.getExternalKey(), false, "La personne n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    System.out.println("PAS DE PERSONNE");
                    return;
                } else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getPersonneId(),enqueteBatimentPayload.getTerminalId());
                    if (optionalPersonne.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                                enqueteBatimentPayload.getExternalKey(), false, "La personne précisée n'existe pas.");
                        syncResponses.add(syncResponse);
                        System.out.println("PAS DE PERSONNE");
                        return;
                    }
                }

                if (enqueteBatimentPayload.getBatimentId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                            enqueteBatimentPayload.getExternalKey(), false, "Le batiment n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    System.out.println("PAS DE BATIMENT");
                    return;
                } else {
                    Optional<Batiment> optionalBatiment = batimentRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getBatimentId(), enqueteBatimentPayload.getTerminalId());
                    if (optionalBatiment.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                                enqueteBatimentPayload.getExternalKey(), false, "Le batiment précisé n'existe pas.");
                        syncResponses.add(syncResponse);
                        System.out.println("PAS DE BATIMENT");
                        return;
                    }
                }

                EnqueteBatiment enqueteBatiment = new EnqueteBatiment();
                enqueteBatimentPayload.setSynchronise(true);
                if (enqueteBatimentPayload.getIdBackend() != null && enqueteBatimentPayload.getIdBackend() != 0) {
                    Optional<EnqueteBatiment> optionalEnqueteBatiment = enqueteBatimentRepository.findById(enqueteBatimentPayload.getIdBackend());
                    if (optionalEnqueteBatiment.isPresent()) {
                        enqueteBatiment = optionalEnqueteBatiment.get();
                        //deleteAllCaracteristiqueBatimentFromEnqueteBatiment(enqueteBatiment);
                        //deleteAllUploadFromEnqueteBatiment(enqueteBatiment);
                    } else {
                        enqueteBatimentPayload.setIdBackend(null);
                    }
                        enqueteBatiment = getEnqueteBatimentFromEnqueteBatimentPayLoad(enqueteBatiment, enqueteBatimentPayload);
                        enqueteBatiment.setStatutEnregistrement(StatutEnregistrement.MISE_A_JOUR);
                        enqueteBatimentRepository.save(enqueteBatiment);
                        enqueteBatimentPayload.setIdBackend(enqueteBatiment.getId());
                } else {
                    Optional<EnqueteBatiment> optionalEnqueteBatiment = enqueteBatimentRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getExternalKey(),enqueteBatimentPayload.getTerminalId());
                    if(optionalEnqueteBatiment.isPresent()){
                            enqueteBatiment = optionalEnqueteBatiment.get();
                           // deleteAllCaracteristiqueBatimentFromEnqueteBatiment(enqueteBatiment);
                           // deleteAllUploadFromEnqueteBatiment(enqueteBatiment);
                    }
                    enqueteBatiment = getEnqueteBatimentFromEnqueteBatimentPayLoad(enqueteBatiment, enqueteBatimentPayload);
                    enqueteBatiment.setStatutEnregistrement(StatutEnregistrement.NOUVELLE_INSERTION);
                    enqueteBatiment = enqueteBatimentRepository.save(enqueteBatiment);
                    enqueteBatimentPayload.setIdBackend(enqueteBatiment.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(enqueteBatimentPayload.getObservation());
                syncResponse.setExternalKey(enqueteBatimentPayload.getExternalKey());
                syncResponse.setSynchronise(enqueteBatimentPayload.isSynchronise());
                syncResponse.setIdBackend(enqueteBatimentPayload.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(enqueteBatimentPayload.getIdBackend(),
                        enqueteBatimentPayload.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    @Override
    public List<SyncResponse> syncEnqueteUniteLogement(List<EnqueteUniteLogementPayload> enqueteUniteLogementPayloads) {
        List<SyncResponse> syncResponses = new ArrayList<>();
        if (enqueteUniteLogementPayloads == null) {
            SyncResponse syncResponse = new SyncResponse(null,
                    null, false, "Aucune enquête d'unité de logement à synchroniser");
            syncResponses.add(syncResponse);
            return syncResponses;
        }
        enqueteUniteLogementPayloads.forEach(enqueteUniteLogementPayload -> {

            try {
                if (enqueteUniteLogementPayload.getTerminalId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                            enqueteUniteLogementPayload.getExternalKey(), false, "Le terminal n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Tpe> optionalTpe = tpeRepository.findById(enqueteUniteLogementPayload.getTerminalId());
                    if (optionalTpe.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                                enqueteUniteLogementPayload.getExternalKey(), false, "Le terminal n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (enqueteUniteLogementPayload.getUserId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                            enqueteUniteLogementPayload.getExternalKey(), false, "L'enquêteur n'est pas précisé");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<User> optionalUser = userRepository.findById(enqueteUniteLogementPayload.getUserId());
                    if (optionalUser.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                                enqueteUniteLogementPayload.getExternalKey(), false, "L'enquêteur précisé n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enqueteUniteLogementPayload.getEnqueteId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                            enqueteUniteLogementPayload.getExternalKey(), false, "L'enquete de la parcelle n'est pas précisée");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getEnqueteId(), enqueteUniteLogementPayload.getTerminalId());
                    if (optionalEnquete.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                                enqueteUniteLogementPayload.getExternalKey(), false, "L'enquete de la parcelle précisée n'existe pas");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }
                if (enqueteUniteLogementPayload.getPersonneId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                            enqueteUniteLogementPayload.getExternalKey(), false, "La personne n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getPersonneId(),enqueteUniteLogementPayload.getTerminalId());
                    if (optionalPersonne.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                                enqueteUniteLogementPayload.getExternalKey(), false, "La personne précisée n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                if (enqueteUniteLogementPayload.getUniteLogementId() == null) {
                    SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                            enqueteUniteLogementPayload.getExternalKey(), false, "L'unité de logement n'est pas précisée.");
                    syncResponses.add(syncResponse);
                    return;
                } else {
                    Optional<UniteLogement> optionalUniteLogement = uniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getUniteLogementId(), enqueteUniteLogementPayload.getTerminalId());
                    if (optionalUniteLogement.isEmpty()) {
                        SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                                enqueteUniteLogementPayload.getExternalKey(), false, "L'unité de logement précisée n'existe pas.");
                        syncResponses.add(syncResponse);
                        return;
                    }
                }

                EnqueteUniteLogement enqueteUniteLogement = new EnqueteUniteLogement();
                enqueteUniteLogementPayload.setSynchronise(true);
                if (enqueteUniteLogementPayload.getIdBackend() != null && enqueteUniteLogementPayload.getIdBackend() != 0) {
                    Optional<EnqueteUniteLogement> optionalEnqueteUniteLogement = enqueteUniteLogementRepository.findById(enqueteUniteLogementPayload.getIdBackend());
                    if (optionalEnqueteUniteLogement.isPresent()) {
                        enqueteUniteLogement = optionalEnqueteUniteLogement.get();
                        //deleteAllCaracteristiqueUniteLogementFromEnqueteUniteLogement(enqueteUniteLogement);
                        //deleteAllUploadFromEnqueteUniteLogement(enqueteUniteLogement);
                    } else {
                        enqueteUniteLogementPayload.setIdBackend(null);
                    }
                            enqueteUniteLogement = getEnqueteUniteLogementFromEnqueteUniteLogementPayLoad(enqueteUniteLogement, enqueteUniteLogementPayload);
                            enqueteUniteLogement.setStatutEnregistrement(StatutEnregistrement.MISE_A_JOUR);
                            enqueteUniteLogementRepository.save(enqueteUniteLogement);
                            enqueteUniteLogementPayload.setIdBackend(enqueteUniteLogement.getId());
                } else {
                    Optional<EnqueteUniteLogement> optionalEnqueteUniteLogement = enqueteUniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getExternalKey(),enqueteUniteLogementPayload.getTerminalId());
                    if(optionalEnqueteUniteLogement.isPresent()){
                        enqueteUniteLogement = optionalEnqueteUniteLogement.get();
                        //deleteAllCaracteristiqueUniteLogementFromEnqueteUniteLogement(enqueteUniteLogement);
                        //deleteAllUploadFromEnqueteUniteLogement(enqueteUniteLogement);
                    } else {
                        enqueteUniteLogementPayload.setIdBackend(null);
                    }
                    enqueteUniteLogement = getEnqueteUniteLogementFromEnqueteUniteLogementPayLoad(enqueteUniteLogement, enqueteUniteLogementPayload);
                    enqueteUniteLogement.setStatutEnregistrement(StatutEnregistrement.NOUVELLE_INSERTION);
                    enqueteUniteLogement = enqueteUniteLogementRepository.save(enqueteUniteLogement);
                    enqueteUniteLogementPayload.setIdBackend(enqueteUniteLogement.getId());
                }
                SyncResponse syncResponse = new SyncResponse();
                syncResponse.setObservation(enqueteUniteLogementPayload.getObservation());
                syncResponse.setExternalKey(enqueteUniteLogementPayload.getExternalKey());
                syncResponse.setSynchronise(enqueteUniteLogementPayload.isSynchronise());
                syncResponse.setIdBackend(enqueteUniteLogementPayload.getIdBackend());
                syncResponses.add(syncResponse);
            } catch (Exception e) {
                e.printStackTrace();
                SyncResponse syncResponse = new SyncResponse(enqueteUniteLogementPayload.getIdBackend(),
                        enqueteUniteLogementPayload.getExternalKey(), false, "Erreur inattendue");
                syncResponses.add(syncResponse);
            }
        });

        return syncResponses;
    }

    private EnqueteUniteLogement getEnqueteUniteLogementFromEnqueteUniteLogementPayLoad(EnqueteUniteLogement enqueteUniteLogement, EnqueteUniteLogementPayload enqueteUniteLogementPayload) {

        if (enqueteUniteLogementPayload.getPersonneId() != null) {
            Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getPersonneId(), enqueteUniteLogementPayload.getTerminalId());
            enqueteUniteLogement.setPersonne(optionalPersonne.orElse(null));
        }

        if (enqueteUniteLogementPayload.getUniteLogementId() != null) {
            Optional<UniteLogement> optionalUniteLogement = uniteLogementRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getUniteLogementId(), enqueteUniteLogementPayload.getTerminalId());
            enqueteUniteLogement.setUniteLogement(optionalUniteLogement.orElse(null));
        }

        if (enqueteUniteLogementPayload.getEnqueteId() != null) {
            Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(enqueteUniteLogementPayload.getEnqueteId(), enqueteUniteLogementPayload.getTerminalId());
            enqueteUniteLogement.setEnquete(optionalEnquete.orElse(null));
        }
        if (enqueteUniteLogementPayload.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(enqueteUniteLogementPayload.getTerminalId());
            enqueteUniteLogement.setTerminal(optionalTpe.orElse(null));
        }

        if (enqueteUniteLogementPayload.getUserId() != null) {
            Optional<User> optionalUser = userRepository.findById(enqueteUniteLogementPayload.getUserId());
            enqueteUniteLogement.setUser(optionalUser.orElse(null));
        }

        enqueteUniteLogement.setEnqueteExternalKey(enqueteUniteLogementPayload.getEnqueteId());
        enqueteUniteLogement.setSurface(enqueteUniteLogementPayload.getSurface());
        enqueteUniteLogement.setNbrePiece(enqueteUniteLogementPayload.getNbrePiece());
        enqueteUniteLogement.setNbreHabitant(enqueteUniteLogementPayload.getNbreHabitant());
        enqueteUniteLogement.setNbreMenage(enqueteUniteLogementPayload.getNbreMenage());
        enqueteUniteLogement.setEnLocation(enqueteUniteLogementPayload.isEnLocation());
        enqueteUniteLogement.setMontantMensuelLoyer(enqueteUniteLogementPayload.getMontantMensuelLoyer());
        enqueteUniteLogement.setNbreMoisEnLocation(enqueteUniteLogementPayload.getNbreMoisEnLocation());
        enqueteUniteLogement.setMontantLocatifAnnuelDeclare(enqueteUniteLogementPayload.getMontantLocatifAnnuelDeclare());
        enqueteUniteLogement.setSurfaceLouee(enqueteUniteLogementPayload.getSurfaceLouee());
        enqueteUniteLogement.setSbee(enqueteUniteLogementPayload.isSbee());
        enqueteUniteLogement.setSoneb(enqueteUniteLogementPayload.isSoneb());
        enqueteUniteLogement.setNumCompteurSbee(enqueteUniteLogementPayload.getNumCompteurSbee());
        enqueteUniteLogement.setNumCompteurSoneb(enqueteUniteLogementPayload.getNumCompteurSoneb());
        enqueteUniteLogement.setDateDebutExcemption(enqueteUniteLogementPayload.getDateDebutExcemption());
        enqueteUniteLogement.setDateFinExcemption(enqueteUniteLogementPayload.getDateFinExcemption());

        enqueteUniteLogement.setExternalKey(enqueteUniteLogementPayload.getExternalKey());
        enqueteUniteLogement.setPersonneExternalKey(enqueteUniteLogementPayload.getPersonneId());
        enqueteUniteLogement.setUniteLogementExternalKey(enqueteUniteLogementPayload.getUniteLogementId());

        return enqueteUniteLogement;
    }

    private void deleteAllUploadFromEnqueteUniteLogement(EnqueteUniteLogement enqueteUniteLogement) {
    }


    private void deleteAllUploadFromEnqueteBatiment(EnqueteBatiment enqueteBatiment) {
        uploadRepository.deleteAllByEnqueteBatiment(enqueteBatiment);
    }

    private EnqueteBatiment getEnqueteBatimentFromEnqueteBatimentPayLoad(EnqueteBatiment enqueteBatiment, EnqueteBatimentPayload enqueteBatimentPayload) {
        System.out.println(enqueteBatimentPayload);
        enqueteBatiment.setSurfaceAuSol(enqueteBatimentPayload.getSurfaceAuSol());
        enqueteBatiment.setAutreMenuisierie(enqueteBatimentPayload.getAutreMenuisierie());
        enqueteBatiment.setAutreMur(enqueteBatimentPayload.getAutreMur());
        enqueteBatiment.setSbee(enqueteBatimentPayload.isSbee());
        enqueteBatiment.setNumCompteurSbee(enqueteBatimentPayload.getNumCompteurSbee());
        enqueteBatiment.setSoneb(enqueteBatimentPayload.isSoneb());
        enqueteBatiment.setNumCompteurSoneb(enqueteBatimentPayload.getNumCompteurSoneb());
        enqueteBatiment.setNbreLotUnite(enqueteBatimentPayload.getNbreLotUnite());
        enqueteBatiment.setNbreUniteLocation(enqueteBatimentPayload.getNbreUniteLocation());
        enqueteBatiment.setSurfaceLouee(enqueteBatimentPayload.getSurfaceLouee());
        enqueteBatiment.setNbreMenage(enqueteBatimentPayload.getNbreMenage());
        enqueteBatiment.setNbreHabitant(enqueteBatimentPayload.getNbreHabitant());
        enqueteBatiment.setValeurMensuelleLocation(enqueteBatimentPayload.getValeurMensuelleLocation());
        enqueteBatiment.setNbreMoisLocation(enqueteBatimentPayload.getNbreMoisLocation());
        enqueteBatiment.setAutreCaracteristiquePhysique(enqueteBatimentPayload.getAutreCaracteristiquePhysique());
        enqueteBatiment.setDateDebutExcemption(enqueteBatimentPayload.getDateDebutExcemption());
        enqueteBatiment.setDateFinExcemption(enqueteBatimentPayload.getDateFinExcemption());
        enqueteBatiment.setExternalKey(enqueteBatimentPayload.getExternalKey());
        enqueteBatiment.setEnqueteExternalKey(enqueteBatimentPayload.getEnqueteId());
        enqueteBatiment.setPersonneExternalKey(enqueteBatimentPayload.getPersonneId());
        enqueteBatiment.setBatimentExternalKey(enqueteBatimentPayload.getBatimentId());

        if (enqueteBatimentPayload.getPersonneId() != null) {
            Optional<Personne> optionalPersonne = personneRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getPersonneId(), enqueteBatimentPayload.getTerminalId());
            enqueteBatiment.setPersonne(optionalPersonne.orElse(null));
        }

        if (enqueteBatimentPayload.getBatimentId() != null) {
            Optional<Batiment> optionalBatiment = batimentRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getBatimentId(), enqueteBatimentPayload.getTerminalId());
            enqueteBatiment.setBatiment(optionalBatiment.orElse(null));
        }

        if (enqueteBatimentPayload.getEnqueteId() != null) {
            Optional<Enquete> optionalEnquete = enqueteRepository.findFirstByExternalKeyAndTerminal_Id(enqueteBatimentPayload.getEnqueteId(), enqueteBatimentPayload.getTerminalId());
            enqueteBatiment.setEnquete(optionalEnquete.orElse(null));
        }
        if (enqueteBatimentPayload.getTerminalId() != null) {
            Optional<Tpe> optionalTpe = tpeRepository.findById(enqueteBatimentPayload.getTerminalId());
            enqueteBatiment.setTerminal(optionalTpe.orElse(null));
        }

        if (enqueteBatimentPayload.getUserId() != null) {
            Optional<User> optionalUser = userRepository.findById(enqueteBatimentPayload.getUserId());
            enqueteBatiment.setUser(optionalUser.orElse(null));
        }

        return enqueteBatiment;
    }
}
