package com.iqser.red.service.persistence.management.v1.processor.service.queue;

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration;
import com.iqser.red.service.persistence.management.v1.processor.model.image.VisualLayoutParsingServiceResponse;
import com.iqser.red.service.persistence.management.v1.processor.service.FileStatusProcessingUpdateService;
import com.iqser.red.service.persistence.management.v1.processor.service.FileStatusService;
import com.iqser.red.service.persistence.service.v1.api.shared.model.dossiertemplate.dossier.file.FileErrorInfo;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class VisualLayoutParsingMessageReceiver {

    public static final String VISUAL_LAYOUT_PARSING_RESPONSE_LISTENER_ID = "visual-layout-parsing-response-listener";

    private final ObjectMapper objectMapper;
    private final FileStatusService fileStatusService;
    private final FileStatusProcessingUpdateService fileStatusProcessingUpdateService;


    @SneakyThrows
    @RabbitListener(id = VISUAL_LAYOUT_PARSING_RESPONSE_LISTENER_ID)
    public void receive(VisualLayoutParsingServiceResponse response) {

        fileStatusService.setStatusAnalyse(response.getDossierId(), response.getFileId(), false);

        log.info("Received message from exchange {} for dossierId {} and fileId {}",
                 MessagingConfiguration.VISUAL_LAYOUT_PARSING_RESPONSE_EXCHANGE,
                 response.getDossierId(),
                 response.getFileId());
    }


    @SneakyThrows
    @RabbitListener(queues = MessagingConfiguration.VISUAL_LAYOUT_PARSING_DLQ)
    public void handleDLQMessage(Message failedMessage) {

        var response = objectMapper.readValue(failedMessage.getBody(), VisualLayoutParsingServiceResponse.class);

        log.warn("Received message from {} for dossierId {} and fileId {}", MessagingConfiguration.VISUAL_LAYOUT_PARSING_DLQ, response.getDossierId(), response.getFileId());
        fileStatusProcessingUpdateService.analysisFailed(response.getDossierId(),
                                                         response.getFileId(),
                                                         new FileErrorInfo("table extractor failed",
                                                                           MessagingConfiguration.VISUAL_LAYOUT_PARSING_DLQ,
                                                                           "table-extractor",
                                                                           OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS)));

    }

}