/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.service.sysmgr.config;

import com.crunii.micro.common.ftp.FTPClientFactory;
import com.crunii.micro.common.ftp.FTPClientPoolFactory;
import com.crunii.micro.common.ftp.FtpRemoteFile;
import com.crunii.micro.common.ftp.RemoteFile;
import com.crunii.micro.common.pool.PoolConfig;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 田平 create 2019年5月24日下午2:47:05
 */
@Configuration
@ConditionalOnProperty(name = "spring.ftp.host")
public class FtpRemoteFileConfiguration {

	@Value("${spring.ftp.host}")
	private String ftpHost;
	@Value("${spring.ftp.port}")
	private int ftpPort;
	@Value("${spring.ftp.username}")
	private String ftpUsername;
	@Value("${spring.ftp.password}")
	private String ftpPassword;

	@Bean(name = "remoteFile")
	public RemoteFile regFtpRemoteFile() throws Exception {
		FtpRemoteFile remoteFile = new FtpRemoteFile(initFtpPoolFactory().getObject());
		return remoteFile;
	}

	@Bean(name = "ftpPoolFactory")
	public FTPClientPoolFactory initFtpPoolFactory() {
		FTPClientPoolFactory poolFactory = new FTPClientPoolFactory();
		poolFactory.setConfig(initFtpPoolConf());
		poolFactory.setClientFactory(initFtpFactory());
		return poolFactory;
	}

	@Bean(name = "ftpPoolConf")
	public GenericObjectPoolConfig<FTPClient> initFtpPoolConf() {
		GenericObjectPoolConfig<FTPClient> config = new GenericObjectPoolConfig<>();
		// sftp的最大channel数不要设置太大，ssh服务一般有限制
		config.setMaxTotal(20);
		config.setMaxIdle(PoolConfig.DEFAULT_MAX_IDLE);
		config.setMinIdle(PoolConfig.DEFAULT_MIN_IDLE);
		config.setMaxWaitMillis(PoolConfig.DEFAULT_MAX_WAIT_MILLIS);
		config.setMinEvictableIdleTimeMillis(PoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
		config.setSoftMinEvictableIdleTimeMillis(PoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
		config.setTimeBetweenEvictionRunsMillis(PoolConfig.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
		config.setTestOnBorrow(PoolConfig.DEFAULT_TEST_ON_BORROW);
		config.setTestOnReturn(PoolConfig.DEFAULT_TEST_ON_RETURN);
		config.setTestOnCreate(PoolConfig.DEFAULT_TEST_ON_CREATE);
		return config;
	}

	@Bean(name = "ftpFactory")
	public FTPClientFactory initFtpFactory() {
		FTPClientFactory channelSftpFactory = new FTPClientFactory();
		channelSftpFactory.setHost(ftpHost);
		channelSftpFactory.setPort(ftpPort);
		channelSftpFactory.setUsername(ftpUsername);
		channelSftpFactory.setPassword(ftpPassword);
		return channelSftpFactory;
	}
}
