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

import com.vrt.fileprotection.FileProtector;
import com.vrt.fileprotection.audio.AudioLocalSearch;
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.entity.file.FileEntity;
import ru.soune.nocopy.service.file.FileEntityService;
import ru.soune.nocopy.service.file.cloud.CloudStorageService;
import ru.soune.nocopy.util.FileUtil;

import java.io.IOException;

@Slf4j
@Service
@RequiredArgsConstructor
public class AudioLocalSearchImpl implements AudioLocalSearch {

    private final FileEntityService fileEntityService;

    private final FileUtil fileUtil;

    private final CloudStorageService cloudStorageService;

    @Override
    public @Nullable FileProtector.FileInfo findBySignature(@NotNull String signature) {
        FileEntity fileEntity = fileEntityService.findBySignature(signature);

        if (fileEntity == null) return null;

        return fileUtil.createFileInfo(fileEntity, null);
    }

    @Override
    public void updateSignature(@NotNull String signature, @NotNull FileProtector.FileInfo fileInfo) {
        try {
            FileEntity fileEntity = fileEntityService.updateSignature(signature, fileInfo.getId());

            cloudStorageService.saveFilesToStorage(fileEntity.getMimeType(), fileEntity.getFileExtension(),
                    fileEntity.getProtectedFilePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
