package com.bcxin.signature.util.ftp;


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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <b> 批量上传 </b>
 * @author ZXF
 * @create 2023/07/07 0007 13:43
 * @version
 * @注意事项 </b>
 */
public class FtpWriteUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpWriteUtil.class);


    /**
     * <b> 将base64字符流写入指定文件 </b>
     * @author ZXF
     * @create 2024/11/27 0027 8:46
     * @version
     * @注意事项 </b>
     */
    public static boolean uploadBase64(String ftpPath, String ftpFileName, String base64Content) {
        boolean result = RetryUtil.execute(() -> {
            FtpWriteConnection ftp = new FtpWriteConnection();//获取ftp con
            try {
                //创建n个ftp链接
                return uploadBase64(ftp, ftpPath, ftpFileName, base64Content);
            } catch (Exception ex) {
                throw new SaasRetryableException(String.format("Retry with %s msg=%s", ftpFileName, ex.getMessage()), ex);
            } finally {
                try {
                    ftp.disconnect();
                } catch (IOException e) {
                    logger.error("=======>释放连接发生异常（ftpPath={}, ftpFileName={}）", ftpPath, ftpFileName, e);
                }
            }
        });

        return result;
    }

    /**
     * <b> 获取ftp目录下所有最近5分钟内生成的文件的文件名，返回文件名列表 </b>
     * @author ZXF
     * @create 2024/11/27 0027 8:44
     * @version
     * @注意事项 </b>
     */
    public static List<String> filenames(String path,String keywork) {
        try {
            //创建n个ftp链接
            FtpWriteFactory factory = new FtpWriteFactory();//连接FTP
            FtpWriteConnection ftp = factory.getFtp();//获取ftp con
            return ftp.fileNames(path,keywork);
        } catch (IOException e) {
            logger.error("filenames failed to get filename:{}",path,e);
        }
        return new ArrayList<>();
    }

    public static boolean uploadBase64(FtpWriteConnection ftp,String ftpPath, String ftpFileName, String base64Content) {
        boolean result = false;
        try {
            //创建n个ftp链接
            result = ftp.uploadBase64(ftpPath, ftpFileName, base64Content);
        } catch (IOException e) {
            logger.error("=======>failed to upload base64 file ftp exception（ftpPath={}, ftpFileName={}）", ftpPath, ftpFileName, e);
        }

        return result;
    }
}
