package ru.soune.nocopy.service.file.impl;

import com.vrt.fileprotection.FileProtector;
import com.vrt.fileprotection.image.ImageLocalSearch;
import com.vrt.fileprotection.image.phash.PHash;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.file.SimilarFileDTO;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.file.ImageHashEntity;
import ru.soune.nocopy.repository.FileEntityRepository;
import ru.soune.nocopy.repository.ImageHashRepository;
import ru.soune.nocopy.service.FileSimilarityService;
import ru.soune.nocopy.util.FileUtil;

import java.util.List;
@Slf4j
@Service
@RequiredArgsConstructor
public class ImageLocalSearchImpl implements ImageLocalSearch {

    private final FileSimilarityService fileSimilarityService;

    private final ImageHashRepository imageHashRepository;

    private final FileUtil fileUtil;

    private final FileEntityRepository fileEntityRepository;

    @Override
    public @NotNull List<Result> find(@NotNull FileProtector.FileInfo fileInfo) {
        List<SimilarFileDTO> duplicateByHammingDistance =
                fileSimilarityService.findDuplicateByHammingDistance(fileInfo.getId(), 10,
                        5, 10);

        return duplicateByHammingDistance.stream()
                .map(fileUtil::convertToResult)
                .toList();
    }

    @Override
    public @Nullable FileProtector.FileInfo findByPHash(@NotNull PHash pHash) {
        ImageHashEntity imageHashEntity =
                imageHashRepository.findByHash64HiAndHash64Lo(pHash.getFirstPart(), pHash.getSecondPart());

        if (imageHashEntity == null) return null;

        FileEntity file = fileEntityRepository.findByFileId(imageHashEntity.getFileId());

        return new FileProtector.FileInfo(FileProtector.Type.IMAGE, imageHashEntity.getFileId(),
                String.valueOf(file.getUserId()), null);
    }
}
