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 org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
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 = "hdfs")
public class HdfsUploadAndDownloadService implements UploadAndDownloadService {
    private static final Logger logger = LoggerFactory.getLogger(HdfsUploadAndDownloadService.class);
    private final UploaderConfiguration uploaderConfiguration;
    private final Configuration configuration;

    public HdfsUploadAndDownloadService(UploaderConfiguration uploaderConfiguration) throws IOException {
        this.uploaderConfiguration = uploaderConfiguration;
        this.configuration = new Configuration();
    }

    @Override
    public void upload(String filename, InputStream inputStream) throws Exception {
        try (FileSystem fileSystem = FileSystem.get(configuration)) {
            fileSystem.mkdirs(new Path(uploaderConfiguration.getTmpDir()));
            FSDataOutputStream outputStream = fileSystem.create(new Path(uploaderConfiguration.getTmpDir(), filename), true);
            IoUtil.copy(inputStream, outputStream);
        }
    }

    @Override
    public void download(String filename, OutputStream outputStream) throws Exception {
        try (FileSystem fileSystem = FileSystem.get(configuration)) {
            FSDataInputStream inputStream = fileSystem.open(new Path(uploaderConfiguration.getTmpDir(), filename));
            IoUtil.copy(inputStream, outputStream);
        }
    }
}
