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

import cn.hutool.core.io.file.FileNameUtil;
import com.lanyuanxiaoyao.service.uploader.configuration.UploaderConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 处理上传事宜
 *
 * @author lanyuanxiaoyao
 * @date 2024-01-24
 */
@Service
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) {
        this.uploaderConfiguration = uploaderConfiguration;
        configuration = new Configuration();
    }

    @Override
    public void download(String path) throws Exception {
        String filename = FileNameUtil.getName(path);
        try (FileSystem fileSystem = FileSystem.get(configuration)) {
            fileSystem.copyToLocalFile(new Path(path), new Path(uploaderConfiguration.getTmpDir(), filename));
        }
    }

    @Override
    public void upload(String filename, String targetPath) throws Exception {
        try (FileSystem fileSystem = FileSystem.get(configuration)) {
            fileSystem.copyFromLocalFile(new Path(uploaderConfiguration.getTmpDir(), filename), new Path(targetPath, filename));
        }
    }
}
