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

import com.iqser.red.service.persistence.management.v1.processor.service.download.DownloadCompressingService;
import com.iqser.red.service.persistence.management.v1.processor.service.download.DownloadPreparationService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DownloadStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.DownloadRedactionFileStatusRepository;
import com.iqser.red.service.persistence.management.v1.processor.utils.TenantUtils;
import com.iqser.red.service.persistence.service.v1.api.shared.model.download.DownloadStatusValue;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.TenantProvider;

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

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

@Slf4j
@RequiredArgsConstructor
@Service
@DisallowConcurrentExecution
public class DownloadReadyJob implements Job {

    private final DownloadStatusPersistenceService downloadStatusPersistenceService;
    private final DownloadRedactionFileStatusRepository downloadRedactionFileStatusRepository;
    private final DownloadCompressingService downloadCompressingService;
    private final TenantProvider tenantProvider;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

        log.debug("Running DownloadReadyJob");

        tenantProvider.getTenants()
                .forEach(tenant -> {

                    if (!TenantUtils.isTenantReadyForPersistence(tenant)) {
                        return;
                    }

                    TenantContext.setTenantId(tenant.getTenantId());

                    downloadStatusPersistenceService.getStatus()
                            .stream()
                            .filter(d -> d.getStatus().equals(DownloadStatusValue.GENERATING))
                            .forEach(download -> {

                                int numberOfFiles = download.getFiles().size();
                                var downloadRedactionFileStatus = downloadRedactionFileStatusRepository.findAllByDownloadStorageId(download.getStorageId());
                                if (downloadRedactionFileStatus.size() >= numberOfFiles) {
                                    downloadCompressingService.markDownloadForCompression(download.getStorageId(), download.getUserId());
                                }
                            });
                });

    }

}
