package com.dxhy.oss.utils;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.util.Properties;

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

    private SshProperties ossConfig;

    public SshFactory(SshProperties ossConfig) {
        this.ossConfig = ossConfig;
    }

    @Override
    public ChannelSftp create() throws SftpPoolException {
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(ossConfig.getUsername(), ossConfig.getHostname(), Integer.parseInt(ossConfig.getPort()));
            // 设置密码
            if (ossConfig.getPassword() != null) {
                session.setPassword(ossConfig.getPassword());
            }
            // 设置密码
            if (ossConfig.getPassword() != null) {
                session.setPassword(ossConfig.getPassword());
            }
            // 为Session对象设置properties
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // 设置超时时间
            session.setTimeout(Integer.parseInt(ossConfig.getTimeout()));
            // 建立链接
            session.connect();
            // 打开SFTP通道
            ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
            // 建立SFTP通道的连接
            channel.connect();
            return channel;
        } catch (JSchException e) {
            throw new SftpPoolException("获取ftp连接失败", e);
        }
    }

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

    // 销毁对象
    @Override
    public void destroyObject(PooledObject<ChannelSftp> p) {
        ChannelSftp channelSftp = p.getObject();
        channelSftp.disconnect();
    }

}