package ru.soune.nocopy.service;

import com.vrt.fileprotection.image.phash.PHash;
import com.vrt.fileprotection.image.phash.PerceptualHashHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.entity.file.ImageHashEntity;
import ru.soune.nocopy.repository.ImageHashRepository;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.Map;

@Service
@RequiredArgsConstructor
@Slf4j
public class ImageHashService {

    private final ImageHashRepository repository;

    public Map<String, Long> calculateHash(Path imagePath) throws IOException {
        File file = imagePath.toFile();

        PHash pHash = PerceptualHashHelper.INSTANCE.generateDCTPerceptualHash(file);

        Long firstPart = pHash.getFirstPart();
        Long secondPart = pHash.getSecondPart();
        Map<String, Long> hash = Map.of(
                "hi", firstPart,
                "low", secondPart);

        return hash;
    }

    public void create(FileEntity file,  Map<String, Long> stringIntegerMap) {
        ImageHashEntity entity = ImageHashEntity.builder()
                .file(file)
                .hash64Hi(stringIntegerMap.get("hi"))
                .hash64Lo(stringIntegerMap.get("low"))
                .hashAlgorithm("PHASH64")
                .createdAt(LocalDateTime.now())
                .build();

        repository.save(entity);
    }
}
