package com.eactive.eai.rms.onl.common.util;

import java.io.File;
import java.io.FileInputStream;

import com.eactive.eai.rms.onl.common.exception.BizException;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;

public class SFtpUtil {
	private static final int FTP_TIME_OUT = 10 * 1000;
	private static final int DEFAULT_PORT = 22;
	
	private String ftpIp;
	private int    ftpPort;
	private String ftpUser;
	private String ftpPass;
	
	public SFtpUtil(String ip, String user, String pass) {
		this.ftpIp   = ip;
		this.ftpUser = user;
		this.ftpPass = pass;
	}
	
	public SFtpUtil(String ip, int port, String user, String pass) {
		this.ftpIp   = ip;
		this.ftpPort = port;
		this.ftpUser = user;
		this.ftpPass = pass;
	}

	public static ChannelSftp sftpConnection(String ip, String user, String pass) throws BizException, JSchException {
		return sftpConnection(ip, DEFAULT_PORT, user, pass);
	}
	
	public static ChannelSftp sftpConnection(String ip, int port, String user, String pass) throws BizException, JSchException {
		Session session = null;
		ChannelSftp sftpChannel = null;
		JSch jsch = new JSch();

		session = jsch.getSession(user, ip, port);
		session.setPassword(pass);
		session.setConfig("StrictHostKeyChecking", "no");
		session.setTimeout(FTP_TIME_OUT);
		session.connect();
		
		sftpChannel = (ChannelSftp) session.openChannel("sftp");
		sftpChannel.connect();
		
		if (!sftpChannel.isConnected()) {
			throw new BizException("SFTP 비정상적으로 연결되어 종료됩니다.");
		}
		
		return sftpChannel;
	}
	
	public static void sftpClose(ChannelSftp sftpChannel) throws JSchException {
		Session session = null; 
				
		if (sftpChannel != null) {
			session = sftpChannel.getSession();
			
			sftpChannel.quit();
			sftpChannel.disconnect();
		}
		
		if (session != null) {
			session.disconnect();
		}
	}
	
	public boolean sftpPutFile(String serverPath, String clientPath, boolean isChmod) throws BizException, Exception {
		boolean ret = false;
		
		ChannelSftp sftpChannel = null;
		FileInputStream in = null;
		try {
			
			if (this.ftpPort == 0) {
				sftpChannel = sftpConnection(ftpIp, ftpUser, ftpPass);
			} else {
				sftpChannel = sftpConnection(ftpIp, ftpPort, ftpUser, ftpPass);
			}
			
			in = new FileInputStream(new File(clientPath));
			sftpChannel.put(in, serverPath);
			
			SftpATTRS atts = sftpChannel.stat(serverPath);
			
			if (isChmod && atts.getSize() > 0) {
				sftpChannel.chmod(644, serverPath);
			}
		} catch (BizException be) {
			throw be;
		} catch (Exception e) {
			throw e;
		} finally {
			if (in != null) {
				in.close();
			}
			sftpClose(sftpChannel);
		}
		return ret;
	}
}
