package ru.soune.nocopy.service.file;

import com.vrt.NoCopyFileService;
import com.vrt.fileprotection.FileProtector;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.file.ProtectionStatus;
import ru.soune.nocopy.repository.FileEntityRepository;
import ru.soune.nocopy.util.FileUtil;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FileProcessingOrchestrator {

    private final NoCopyFileService noCopyFileService;

    private final FileEntityRepository fileRepository;

    private final FileUtil fileUtil;

    public void initializeProcessingQueue() {
        List<FileEntity> filesToProtect = fileRepository.findByProtectionStatus(ProtectionStatus.NOT_PROTECTED);

        for (FileEntity fileEntity : filesToProtect) {
            try {
                FileProtector.FileInfo fileInfo = fileUtil.createFileInfo(fileEntity);

                noCopyFileService.addFile(fileInfo);

                log.info("Add to query: {}", fileEntity.getOriginalFileName());
            } catch (Exception e) {
                log.error("Fail add to query: {}", fileEntity.getId(), e);
            }
        }
    }

    @Scheduled(fixedDelay = 120000)
    public void checkNewFilesForProtection() {
        List<FileEntity> newFiles = fileRepository.findAllActiveFilesAndNotProtected();

        for (FileEntity fileEntity : newFiles) {
            FileProtector.FileInfo fileInfo = fileUtil.createFileInfo(fileEntity);

            noCopyFileService.addFile(fileInfo);
        }
    }
}
