package kr.co.i4way.util;

import java.util.List;
import java.util.Vector;
import java.io.*;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpUtil {
	private final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());
	public boolean FtpPut(String ip, int port, String id, String password,
			String upload_dir, String makedir, List files){
		boolean result = false;
		FTPClient ftp = null;
		int reply = 0;
		int a=0;
		try{
			ftp = new FTPClient();
			ftp.connect(ip, port);
			
			reply = ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
				return result;
			}

			if(!ftp.login(id,  password)){
				ftp.logout();
				return result;
			}

			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(upload_dir);
			ftp.makeDirectory(makedir);
			ftp.changeWorkingDirectory(makedir);

			for(int i=0; i<files.size(); i++){
				String sourceFile = (String)files.get(i);
				File uploadFile = new File(sourceFile); 
				FileInputStream fis = null;
				try{
					fis = new FileInputStream(uploadFile);
					boolean isSuccess = ftp.storeFile(uploadFile.getName(), fis);
					if(isSuccess){
						logger.info("FTP Upload Success ["+sourceFile+"]");
					}
				}catch(IOException e){
					e.printStackTrace();
				}finally{
					if(fis != null){
						try{
							fis.close();
						}catch(IOException e){
							e.printStackTrace();
						}
					}
				}
			}
			ftp.logout();
			result = true;
		}catch(SocketException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(ftp != null && ftp.isConnected()){
				try{ftp.disconnect(); } catch (IOException e){}
			}
		}
		return result;
	}

	public boolean FtpGet(String ip, int port, String id, String password,
			String local_dir, String server_dir, String remote_fileName, String local_fileName){
		boolean result = false;
		FTPClient ftp = null;
		int reply = 0;
		try{
			ftp = new FTPClient();
			ftp.connect(ip, port);
			logger.info("FTP Connect Success");
			reply = ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				logger.info("FTP Login Fail1");
				ftp.disconnect();
				return result;
			}
			
			if(!ftp.login(id,  password)){
				logger.info("FTP Login Fail2");
				ftp.logout();
				return result;
			}
			logger.info("FTP Login Success");
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(server_dir);
			File f = new File(local_dir, local_fileName);
			FileOutputStream fos = null;
			try{
				fos = new FileOutputStream(f);
				boolean isSuccess = ftp.retrieveFile(remote_fileName, fos);
				result = isSuccess;
				if(isSuccess){
					logger.info("FTP Download Success ["+remote_fileName+"]");
				}else{
					logger.info("FTP Download Fail ["+remote_fileName+"]");
				}
			}catch(IOException e){
				logger.info(getPrintStackTrace(e));
			}finally{
				if(fos != null) try{fos.close();} catch(IOException e){logger.error(getPrintStackTrace(e));}
			}
			ftp.logout();
		}catch(SocketException e){
			logger.error(getPrintStackTrace(e));
		}catch(IOException e){
			logger.error(getPrintStackTrace(e));
		}catch(Exception e){
			logger.error(getPrintStackTrace(e));
		}finally{
			if(ftp != null && ftp.isConnected()){
				try{ftp.disconnect();} catch(IOException e){logger.error(getPrintStackTrace(e));}
			}
		}
		return result;
	}
	
	public Vector getFileInfo(String ip, int port, String id, String password,
			String server_dir){
		Vector vc = new Vector();
		boolean result = false;
		FTPClient ftp = null;
		FTPFile[] files;
		int reply = 0;
		try{
			ftp = new FTPClient();
			ftp.connect(ip, port);
			System.out.println("FTP Connection Success.  IP="+ip);
			reply = ftp.getReplyCode();
			if(!FTPReply.isPositiveCompletion(reply)){
				ftp.disconnect();
			}
			if(!ftp.login(id,  password)){
				ftp.logout();
			}else{
				System.out.println("FTP Login Success.");
			}
			ftp.setFileType(FTP.ASCII_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			ftp.changeWorkingDirectory(server_dir);
			try{
				if(ftp.isConnected()){
					files = ftp.listFiles(server_dir);
					System.out.println(files.length + "Files In Target Folder.");
					for (int i=0; i<files.length; i++){
						vc.addElement(files[i].getName());
					}
				}
			}catch(IOException e){
				e.printStackTrace(); 
			}
		}catch(SocketException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(ftp != null && ftp.isConnected()){
				try{
					ftp.disconnect();} catch(IOException e){e.printStackTrace();}
			}
		}
		return vc;
	}
	
	public static String getPrintStackTrace(Exception e) {
        
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
         
        return errors.toString();
         
    }
}
