package com.lanyuanxiaoyao.service.uploader.service.filesystem;

import cn.hutool.core.io.IoUtil;
import com.lanyuanxiaoyao.service.uploader.configuration.UploaderConfiguration;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

/**
 * 处理上传事宜
 *
 * @author lanyuanxiaoyao
 * @date 2024-01-24
 */
@Service
@ConditionalOnProperty(value = "uploader.backend", havingValue = "local")
public class LocalUploadAndDownloadService implements UploadAndDownloadService {
    private static final Logger logger = LoggerFactory.getLogger(LocalUploadAndDownloadService.class);
    private final UploaderConfiguration uploaderConfiguration;

    public LocalUploadAndDownloadService(UploaderConfiguration uploaderConfiguration) throws IOException {
        this.uploaderConfiguration = uploaderConfiguration;
    }

    @Override
    public void upload(String filename, InputStream inputStream) throws Exception {
        Files.createDirectories(Paths.get(uploaderConfiguration.getTmpDir()));
        IoUtil.copy(inputStream, Files.newOutputStream(Paths.get(uploaderConfiguration.getTmpDir(), filename)));
    }

    @Override
    public void download(String filename, OutputStream outputStream) throws Exception {
        IoUtil.copy(Files.newInputStream(Paths.get(uploaderConfiguration.getTmpDir(), filename)), outputStream);
    }
}
