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

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

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

import com.iqser.red.service.persistence.management.v1.processor.entity.download.DownloadStatusEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.ApplicationConfigService;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.DownloadStatusPersistenceService;
import com.iqser.red.service.persistence.management.v1.processor.utils.TenantUtils;
import com.iqser.red.storage.commons.service.StorageService;
import com.knecon.fforesight.tenantcommons.TenantContext;
import com.knecon.fforesight.tenantcommons.TenantProvider;

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

@Slf4j
@RequiredArgsConstructor
@Service
public class DownloadCleanupJob implements Job {

    private final DownloadStatusPersistenceService downloadStatusPersistenceService;
    private final StorageService storageService;
    private final ApplicationConfigService applicationConfigService;
    private final TenantProvider tenantProvider;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) {

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

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

            TenantContext.setTenantId(tenant.getTenantId());

            var now = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS);
            log.info("Checking for downloads to delete at {}", now);
            List<DownloadStatusEntity> downloadStatusList = downloadStatusPersistenceService.getStatus();
            downloadStatusList.forEach(downloadStatus -> {

                var dossier = downloadStatus.getDossier();
                var applicationConfigurationEntity = applicationConfigService.getApplicationConfig();
                if (downloadStatus.getLastDownload() != null && downloadStatus.getLastDownload()
                        .plusHours(applicationConfigurationEntity.getDownloadCleanupDownloadFilesHours())
                        .isBefore(now)) {
                    log.info("1. Deleting download status {} because DownloadCleanupDownloadFilesHours is {} and c+h {} is after {}",
                            downloadStatus,
                            applicationConfigurationEntity.getDownloadCleanupDownloadFilesHours(),
                            downloadStatus.getCreationDate().plusHours(applicationConfigurationEntity.getDownloadCleanupDownloadFilesHours()),
                            now);
                    deleteDownload(downloadStatus);
                } else if (downloadStatus.getLastDownload() == null && downloadStatus.getCreationDate()
                        .plusHours(applicationConfigurationEntity.getDownloadCleanupNotDownloadFilesHours())
                        .isBefore(now)) {
                    log.info("2. Deleting download status {} because DownloadCleanupNotDownloadFilesHours is {} and c+h {} is after {}",
                            downloadStatus,
                            applicationConfigurationEntity.getDownloadCleanupNotDownloadFilesHours(),
                            downloadStatus.getCreationDate().plusHours(applicationConfigurationEntity.getDownloadCleanupNotDownloadFilesHours()),
                            now);
                    deleteDownload(downloadStatus);
                } else if (dossier != null && dossier.getSoftDeletedTime() != null) {
                    log.info("3. Deleting download {}, because dossier does not exist", downloadStatus.getStorageId());
                    deleteDownload(downloadStatus);
                }
            });
        });
    }


    private void deleteDownload(DownloadStatusEntity downloadStatus) {

        log.info("Deleting download status {}", downloadStatus.getStorageId());
        try {
            storageService.deleteObject(TenantContext.getTenantId(), downloadStatus.getStorageId());
        } catch (Exception e) {
            log.warn("Download could not be deleted: {}" + e.getMessage());
        }
        try {
            downloadStatusPersistenceService.deleteStatus(downloadStatus.getStorageId());
        } catch (Exception e) {
            log.warn("DownloadStatus could not be deleted: {}" + e.getMessage());
        }
    }

}
