package io.gmss.fiscad.service.worker;

import io.gmss.fiscad.entities.infocad.metier.*;
import io.gmss.fiscad.entities.infocad.parametre.ModeAcquisition;
import io.gmss.fiscad.entities.infocad.parametre.Personne;
import io.gmss.fiscad.entities.infocad.parametre.SourceDroit;
import io.gmss.fiscad.entities.infocad.parametre.TypePiece;
import io.gmss.fiscad.entities.metadata.MobileDataPiece;
import io.gmss.fiscad.entities.metadata.MobileDataUpload;
import io.gmss.fiscad.entities.rfu.metier.EnqueteBatiment;
import io.gmss.fiscad.entities.rfu.metier.EnqueteUniteLogement;
import io.gmss.fiscad.enums.TypeObjet;
import io.gmss.fiscad.paylaods.request.PiecePayLoad;
import io.gmss.fiscad.paylaods.request.UploadPayLoad;
import io.gmss.fiscad.repositories.infocad.metier.*;
import io.gmss.fiscad.repositories.infocad.parametre.ModeAcquisitionRepository;
import io.gmss.fiscad.repositories.infocad.parametre.PersonneRepository;
import io.gmss.fiscad.repositories.infocad.parametre.SourceDroitRepository;
import io.gmss.fiscad.repositories.infocad.parametre.TypePieceRepository;
import io.gmss.fiscad.repositories.metadata.MobileDataPieceRepository;
import io.gmss.fiscad.repositories.metadata.MobileDataUploadRepository;
import io.gmss.fiscad.repositories.rfu.metier.EnqueteBatimentRepository;
import io.gmss.fiscad.repositories.rfu.metier.EnqueteUniteLogementRepository;
import io.gmss.fiscad.service.LogService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UploadAsyncWorker {
    private final TpeRepository tpeRepository;
    private final PersonneRepository personneRepository;
    private final EnqueteRepository enqueteRepository;
    private final EnqueteUniteLogementRepository enqueteUniteLogementRepository;
    private final EnqueteBatimentRepository enqueteBatimentRepository;
    private final MembreGroupeRepository membreGroupeRepository;
    private final MobileDataUploadRepository mobileDataUploadRepository;
    private final UploadRepository uploadRepository;
    private final PieceRepository pieceRepository;
    private final LogService logService;
    //@Async("uploadExecutor")
    public void traitementAsyncUpload(MobileDataUpload mobileDataUpload) {
        UploadPayLoad uploadPayLoad = mobileDataUpload.getUploadPayLoad();
        try {
            if (uploadPayLoad.getTerminalId() == null) {
                logService.logTraiementAsync(TypeObjet.UPLOAD, "Problème de terminal", "terminal non fourni : ", mobileDataUpload.getId());
                return;
            } else {
                Optional<Tpe> optionalTpe = tpeRepository.findById(uploadPayLoad.getTerminalId());
                if (optionalTpe.isEmpty()) {
                    logService.logTraiementAsync(TypeObjet.UPLOAD, "Problème de terminal", "terminal inexistant : ", mobileDataUpload.getId());
                    return;
                }
            }
            Upload upload = new Upload();
            upload.setMobileDataId(mobileDataUpload.getId());
            upload = getUploadFromUplaodPayLoad(upload, mobileDataUpload);
            uploadRepository.save(upload);
            mobileDataUpload.setTraiter(true);
            mobileDataUploadRepository.save(mobileDataUpload);
        } catch (Exception e) {
            logService.logTraiementAsync(TypeObjet.UPLOAD, "Problème de inattendu", e.getMessage(), mobileDataUpload.getId());
        }
    }


    public Upload getUploadFromUplaodPayLoad(Upload upload, MobileDataUpload mobileDataUpload) {
        UploadPayLoad uploadPayLoad= mobileDataUpload.getUploadPayLoad();

        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.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(mobileDataUpload.getFileName());
        upload.setMimeType(mobileDataUpload.getMimeType());
        upload.setSize(mobileDataUpload.getSize());
        upload.setOriginalFileName(mobileDataUpload.getOriginalFileName());
        upload.setName(uploadPayLoad.getName());
        upload.setFilePath(mobileDataUpload.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;
    }
}
