package ru.soune.nocopy.util;

import com.vrt.fileprotection.FileProtector;
import com.vrt.fileprotection.image.ImageLocalSearch;
import com.vrt.fileprotection.image.ImageScore;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.dto.file.SimilarFileDTO;
import ru.soune.nocopy.entity.file.FileEntity;

@Service
public class FileUtil {

    public ImageLocalSearch.Result convertToResult(SimilarFileDTO response) {
        FileProtector.FileInfo fileInfo =
                new FileProtector.FileInfo(FileProtector.Type.IMAGE, response.getFileId(),
                        String.valueOf(response.getOwnerId()), null);
        ImageScore imageScore = new ImageScore(ImageScore.Rate.valueOf(response.getSimilarityLevel()),
                response.getHammingDistance());

        return new ImageLocalSearch.Result(fileInfo, imageScore);
    }

    public FileProtector.FileInfo createFileInfo(FileEntity fileEntity, String convertTo) {
        FileProtector.Type type = determineFileType(fileEntity.getMimeType());

        return new FileProtector.FileInfo(type, fileEntity.getId(), String.valueOf(fileEntity.getUserId()), convertTo);
    }

    public int hamming64(long aHi, long aLo, long bHi, long bLo) {
        return Long.bitCount(aHi ^ bHi)
                + Long.bitCount(aLo ^ bLo);
    }

    private FileProtector.Type determineFileType(String mimeType) {
        if (mimeType == null) {
            return FileProtector.Type.IMAGE;
        }

        if (mimeType.startsWith("image")) {
            return FileProtector.Type.IMAGE;
        } else if (mimeType.startsWith("video")) {
            return FileProtector.Type.VIDEO;
        } else if (mimeType.startsWith("audio")) {
            return FileProtector.Type.AUDIO;
        } else if (mimeType.startsWith("document")) {
            return FileProtector.Type.DOC;
        } else {
            return FileProtector.Type.IMAGE;
        }
    }
}
