package com.bcxin.backend.domain.utils.ftp;

import com.bcxin.backend.core.utils.RetryUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;

/**
 * <b> 上传任务 </b>
 * @author ZXF
 * @create 2023/07/07 0007 13:44
 * @version
 * @注意事项 </b>
 */
public class UploadTask implements Callable {
    private static final Logger logger = LoggerFactory.getLogger(UploadTask.class);

    private File file;

    private FtpConnection ftp;

    private String path;

    private String fileName;

    private FtpFactory factory;

    public UploadTask(FtpFactory factory,FtpConnection ftp, File file, String path, String fileName){

        this.factory = factory;

        this.ftp = ftp;

        this.file = file;

        this.path = path;

        this.fileName = fileName;

    }

    @Override
    public UploadResult call() throws Exception {
        UploadResult result = null;
        try {
            if (ftp == null) {
                result = new UploadResult(file.getAbsolutePath(), false);
                return result;
            }
            //如果连接未开启 重新获取连接
            if (!ftp.isConnected()) {
                factory.remove(ftp);
                ftp = new FtpConnection();
            }

            //开始上传
            result = new UploadResult(file.getName(), ftp.upload(path, fileName, file));
        } catch (IOException ex) {
            result = new UploadResult(file.getName(), false);
            logger.error("上传Ftp发生异常:{}", result, ex);
        } finally {
            factory.relase(ftp);//释放连接
        }

        return result;
    }
}
