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 ru.soune.nocopy.service.file.cloud.CloudStorageService;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class ImageHashService {

    private final ImageHashRepository repository;

    private final CloudStorageService cloudStorageService;

    public Map<String, Long> calculateHash(Path imagePath) throws IOException {
        PHash pHash;

        if (imagePath.toFile().exists()) {
            pHash = PerceptualHashHelper.INSTANCE.generateDCTPerceptualHash(imagePath.toFile());
        } else {
            byte[] data = cloudStorageService.readFileFromStorageBytes(imagePath.toString());

            Path tempFile = Files.createTempFile("perceptual_hash_", ".tmp");
            try {
                Files.write(tempFile, data);
                pHash = PerceptualHashHelper.INSTANCE.generateDCTPerceptualHash(tempFile.toFile());
            } finally {
                Files.deleteIfExists(tempFile);
            }
        }

        Long firstPart = pHash.getFirstPart();
        Long secondPart = pHash.getSecondPart();

        return Map.of(
                "hi", firstPart,
                "low", secondPart
        );
    }

    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);
    }
}
