package com.sn.sowsysrestapi.domain.infrastructure.service.storage;

import com.sn.sowsysrestapi.domain.service.PictureStorageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

@Service
public class LocalPictureStorageService implements PictureStorageService {

    @Override
    public void replace(String oldFileName, NewPicture newPicture) {
        PictureStorageService.super.replace(oldFileName, newPicture);
    }

    @Override
    public String generateFileName(String originalName) {
        return PictureStorageService.super.generateFileName(originalName);
    }

    // path below is configured on application.properties
    @Value("${sowsys.storage.local.directory-picture}")
    private Path pictureDirectory;

    @Override
    public InputStream recover(String fileName) {

        try {
            Path filePath = getFilePath(fileName);

            return Files.newInputStream(filePath);
        } catch (Exception e) {
            throw new StorageException("It was not possible to recover the file.", e);
        }

    }

    @Override
    public void store(NewPicture newPicture) {

        try {
            Path filePath = getFilePath(newPicture.getFileName());

            FileCopyUtils.copy(newPicture.getInputStream(),
                    Files.newOutputStream(filePath));
        } catch (IOException e) {
            throw new StorageException("It was not possible to store the file.", e);
        }

    }

    @Override
    public void remove(String fileName) {

        try {
            Path filePath = getFilePath(fileName);
            Files.deleteIfExists(filePath);
        } catch (Exception e) {
            throw new StorageException("It was not possible to delete the file.", e);
        }

    }

    private Path getFilePath(String fileName) {
        return pictureDirectory.resolve(Path.of(fileName));
    }


}
