package biz.comm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class JSCHFTPManager {
	
	private Session session = null; //com.jcraft.jsch.Session 참조함
	//private JSch jsch = null;
	private Channel channel =null;
	private ChannelSftp channelSftp = null;
    
/*
	private SshClient client = null;
	private PasswordAuthenticationClient auth = null;
	private SftpClient sftp = null; 
	*/
	private static Logger logger = Logger.getLogger(JSCHFTPManager.class);

	public JSCHFTPManager(String server, int port, String user, String pwd) throws Exception {
		 
		 JSch jsch = new JSch();
	        try {
	        	logger.debug("init start  --->" );
	            session = jsch.getSession(user,server, port);
	            session.setPassword(pwd);

	            java.util.Properties config = new java.util.Properties();
	            config.put("StrictHostKeyChecking", "no");
	            session.setConfig(config);
	            logger.debug("session connect start  --->" );
	            session.connect(); 
	            logger.debug("session connect end  --->" );
 	            channel = session.openChannel("sftp");
 	            logger.debug("channel open  --->" );
	            channel.connect();
	            logger.debug("channel connect  --->" );
	            
	        } catch (JSchException e) {
	        	 logger.debug("init error  --->" + e.getMessage());
	        	//e.printStackTrace();
	        }

	        channelSftp = (ChannelSftp) channel; 
	}
	
	public JSCHFTPManager() {
		// TODO Auto-generated constructor stub
	}
 
	public void init(String host, String userName, String password, int port) {
        JSch jsch = new JSch();
        try {
        	logger.debug("sftp init start --->");
        	session = jsch.getSession(userName, host, port);
            session.setPassword(password);

            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();
             
        } catch (JSchException e) {
            e.printStackTrace();
            logger.debug("sftp init error --->" + e.getMessage());
        }

        channelSftp = (ChannelSftp) channel; 
        
    }
	
	
	public void upload(String dir, File file) {

        FileInputStream in = null;
        try {
    		logger.debug("ftp Sftp in 1   " + file.getName() ); 
            in = new FileInputStream(file);
    		logger.debug("ftp Sftp in 2   " + dir ); 
            channelSftp.cd(dir);
            logger.debug( "ftp cd complete " + dir ); 
            channelSftp.put(in, file.getName());
            logger.debug( "ftp upload complete1 " + file.getName() ); 
        } catch (SftpException e) {
			logger.debug("ftp SftpException " + e.getMessage() ); 
            e.printStackTrace();
        } catch (FileNotFoundException e) {
			logger.debug("ftp FileNotFoundException " + e.getMessage() ); 
            e.printStackTrace();
        } finally {
            try {
            	if(in != null){
            		in.close();
            		logger.info( "ftp upload complete2 " + dir ); 
            	}
            } catch (IOException e) {
    			logger.error("ftp finally " + e.getMessage() ); 
                e.printStackTrace();
            }
        }
    }
	public  Vector<ChannelSftp.LsEntry> getFileList(String path , String ext ) {
    	
    	Vector<ChannelSftp.LsEntry> list = null;
    	try {
    		channelSftp.cd(path);
    		if(ext.equals("")){
    			list = channelSftp.ls(".");
    		}else{
    			list = channelSftp.ls("." + ext );
    		}
		} catch (SftpException e) {
			logger.error("ftp err " + e.getMessage() ); 
			e.printStackTrace();

			return null;
		}
    	
    	return list;
    }
	public  Vector<ChannelSftp.LsEntry> getFileList(String path ) {
    	
    	Vector<ChannelSftp.LsEntry> list = null;
    	try {
    		channelSftp.cd(path);
     		list = channelSftp.ls(".");
		} catch (SftpException e) {
			logger.error("ftp err " + e.getMessage() ); 
			e.printStackTrace();

			return null;
		}
    	
    	return list;
    }
	public List<ChannelSftp.LsEntry> ls(String ftpDir) throws Exception {
		Vector<ChannelSftp.LsEntry> list = null;
		
		try {
			if(channelSftp != null) { 
				list  = channelSftp.ls(ftpDir);
			}
		}catch(Exception e) {
			logger.error("ftp err1 중" + e.getMessage() ); 

			throw e;
		}
		return list;
	}
	
	public boolean rename(String oldpath, String newpath) throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.rename(oldpath, newpath);
				
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		return bRtn;
	}
	 
	public boolean put(String path) throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.put(path);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		return bRtn;
	}
	
	public boolean get(String srcFile, OutputStream oStream) throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.get(srcFile, oStream);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		
		return bRtn;
	}
	
	public boolean get(String srcFile, String destFile) throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				if(destFile == null)
					channelSftp.get(srcFile);
				else
					channelSftp.get(srcFile, destFile);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		return bRtn;
	}
	
	public boolean lcd(String path) throws Exception
	{
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.lcd(path);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		
		return bRtn;
	}
	
	public boolean cd(String path) throws Exception
	{
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.cd(path);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		
		return bRtn;
	}
	
	public String pwd() throws Exception
	{
		String strRtn = "";
		try {
			if(channelSftp != null) {
				strRtn = channelSftp.pwd();
			}
		}catch(Exception e) {
			throw e;
		}
		
		return strRtn;
	}
	
	public boolean chmod(int permissions, String path) throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null) {
				channelSftp.chmod(permissions, path);
				bRtn = true;
			}
		}catch(Exception e) {
			throw e;
		}
		
		return bRtn;
	}
	
	public boolean isClosed() throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp !=null ) {
				bRtn = channelSftp.isClosed();
			}
		}catch(Exception e) {
			throw e;
		}
		return bRtn;
	}
	
	public boolean logout() throws Exception {
		boolean bRtn = false;
		try {
			if(channelSftp != null)
				channelSftp.quit();
			if(session != null)
				session.disconnect();
			bRtn = true;
		}catch(Exception e) {
			throw e;
		}
		
		return bRtn;
	}
}
