/**
 * 
 */
package org.springblade.etl.engine.datax.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import org.springblade.etl.properties.DsyProperties.ServerInfo;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;

import cn.hutool.core.io.IoUtil;
import cn.hutool.extra.ssh.JschUtil;

/**
 * @author wookvn
 *
 */
public enum DataxSftpKit {

	;
	
	/**
	 * 创建session
	 * @param dsyConfig
	 * @return
	 */
	public static Session createNewSession(ServerInfo serverInfo) {
		return JschUtil.createSession(serverInfo.getIp(), serverInfo.getPort(), serverInfo.getUser(), serverInfo.getPassword());
	}
	
	/**
	 * 创建session
	 * @param dsyConfig
	 * @return
	 */
	public static Session getSession(ServerInfo serverInfo) {
		return JschUtil.getSession(serverInfo.getIp(), serverInfo.getPort(), serverInfo.getUser(), serverInfo.getPassword());
	}
	
	/**
	 * 执行Command命令
	 * @param command
	 */
	public static String execute(Session session, String command, OutputStream os) {
		return JschUtil.exec(session, command, StandardCharsets.UTF_8, os);
	}
	
	/**
	 * 
	 * @param session
	 * @param logName
	 * @return
	 * @throws Exception 
	 */
	public static InputStream download(Session session, String logName) throws Exception {
		ChannelSftp sftpChannel = null;
		try {
			sftpChannel = JschUtil.openSftp(session, 2000);
			ByteArrayInputStream bais = null;
			try(ByteArrayOutputStream baos = new ByteArrayOutputStream()){
				sftpChannel.get(logName, baos);
				bais = new ByteArrayInputStream(baos.toByteArray());
			}
			return bais;
		} finally {
			JschUtil.close(sftpChannel);
		}
	}
	
	/**
	 * 上传文件
	 * @param uploadDir
	 * @param is
	 * @return
	 * @throws Exception 
	 */
	public static boolean upload(Session session, String uploadDir, String dstFileName, InputStream ist) throws Exception {
		ChannelSftp sftpChannel = null;
		try {
			sftpChannel = JschUtil.openSftp(session, 2000);
			//进入指定目录:判断文件夹是否存在
			try {
				sftpChannel.lstat(uploadDir);
				sftpChannel.cd(uploadDir);
			} catch (Exception e) {
				sftpChannel.mkdir(uploadDir);
			}
			sftpChannel.put(ist, uploadDir + "/" + dstFileName);
			return true;
		} finally {
			IoUtil.close(ist);
			JschUtil.close(sftpChannel);
		}
	}
	
	/**
	 * 
	 * @param session
	 */
	public static void closeSession(Session session) {
		JschUtil.close(session);
	}
}
