package com.iqser.red.service.persistence.management.v1.processor.utils;

import java.io.InputStream;

import org.springframework.core.io.FileSystemResource;
import org.springframework.web.context.request.RequestContextHolder;

import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;

@UtilityClass
public final class DownloadBufferUtils {

    public static final String DOWNLOAD_TEMP_FILE_BUFFER_LOCATION = "DOWNLOAD_TEMP_FILE_BUFFER_LOCATION";


    @SneakyThrows
    public static FileSystemResource fileProxyStreamForDownload(InputStream inputStream) {

        var tempFile = FileUtils.createTempFile("download", "pdf");
        org.apache.commons.io.FileUtils.copyInputStreamToFile(inputStream, tempFile);
        inputStream.close();

        if (RequestContextHolder.getRequestAttributes() != null) {
            RequestContextHolder.getRequestAttributes().setAttribute(DOWNLOAD_TEMP_FILE_BUFFER_LOCATION, tempFile.getAbsolutePath(), 0);
        }

        return new FileSystemResource(tempFile);
    }

}
