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

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.configuration.MessagingConfiguration;
import com.iqser.red.service.persistence.management.v1.processor.model.DownloadJob;
import com.iqser.red.service.persistence.management.v1.processor.service.websocket.WebsocketService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.DownloadStatusRepository;
import com.iqser.red.service.persistence.service.v1.api.shared.model.download.DownloadStatusValue;
import com.knecon.fforesight.tenantcommons.TenantContext;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class DownloadCompressingService {

    private final DownloadPreparationService downloadPreparationService;
    private final DownloadStatusRepository downloadStatusRepository;
    private final RabbitTemplate rabbitTemplate;
    private final WebsocketService websocketService;


    public void markDownloadForCompression(String downloadId, String userId) {

        var updated = downloadStatusRepository.updateStatusOnlyIfNotAlreadySet(downloadId, DownloadStatusValue.COMPRESSING);

        if (updated == 1) {
            websocketService.sendDownloadEvent(downloadId, userId, DownloadStatusValue.COMPRESSING);
            rabbitTemplate.convertAndSend(MessagingConfiguration.DOWNLOAD_COMPRESSION_REQUEST_EXCHANGE,
                                          TenantContext.getTenantId(),
                                          DownloadJob.builder().storageId(downloadId).userId(userId).build());
        }
    }


    public void compressDownload(String downloadId) {

        downloadPreparationService.createDownload(downloadId);
        downloadPreparationService.clearRedactionStatusEntries(downloadId);
    }

}
