package com.dxhy.oss.utils;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;

@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public class SftpFactory extends BasePooledObjectFactory<FTPClient> {

    private SftpProperties ossConfig;

    public SftpFactory(SftpProperties ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public FTPClient create() throws Exception{
        FTPClient ftpClient = null;
        try {
            ftpClient = new FTPClient();
            ftpClient.setControlEncoding("UTF-8");// 中文支持
            ftpClient.setConnectTimeout(1000 * 30);//设置连接超时时间
            ftpClient.connect(ossConfig.getHostname(), Integer.valueOf(ossConfig.getPort()));// 连接FTP服务器
            ftpClient.login(ossConfig.getUsername(), ossConfig.getPassword());// 登陆FTP服务器
            // 设置文件类型为二进制（如果从FTP下载或上传的文件是压缩文件的时候，不进行该设置可能会导致获取的压缩文件解压失败）
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//            ftpClient.enterLocalPassiveMode();//开启被动模式，否则文件上传不成功，也不报错
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.info("连接FTP失败，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                log.info("FTP连接成功!");
            }
        } catch (Exception e) {
            log.info("登陆FTP失败，请检查FTP相关配置信息是否正确！" + e);
            return null;
        }
        return ftpClient;
    }


    @Override
    public PooledObject<FTPClient> wrap(FTPClient channelSftp) {
        return new DefaultPooledObject<>(channelSftp);
    }

    // 销毁对象
    @Override
    public void destroyObject(PooledObject<FTPClient> p) {
        FTPClient ftpClient = p.getObject();
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            log.error("登出ftp失败，请检查FTP相关配置信息是否正确！" + e);
        }
    }

}