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

import com.vrt.AudioFilePathProvider;
import com.vrt.fileprotection.FileProtector;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import ru.soune.nocopy.entity.file.FileEntity;
import ru.soune.nocopy.repository.FileEntityRepository;
import ru.soune.nocopy.service.file.FileEntityService;

import java.io.IOException;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class AudioFilePathProviderImpl implements AudioFilePathProvider {

    private final FileEntityService fileEntityService;

    private final FileEntityRepository fileEntityRepository;

    @Override
    public @NotNull String providePath(@NotNull FileProtector.FileInfo fileInfo) {
        String filePath;
        Optional<FileEntity> optionalFileEntity = fileEntityRepository.findById(fileInfo.getId());

        if (optionalFileEntity.isEmpty()) {
            throw new NullPointerException();
        }

        FileEntity fileEntity = optionalFileEntity.get();

        try {
            filePath = fileEntityService.prepareProtectedPath(fileEntity, fileEntity.getFileExtension()).toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return filePath;
    }
}
