package com.asuscomm.ftptest;

import android.util.Log;
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 java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketException;

/** 本類別簡化FTP上傳下載功能
 * 開發日期 : 2017/10/01
 * @author Thomas (mahaljsp@gmail.com)
 */

final public class MahalFtp {
    private FTPClient ftpClient = null;
    //private static MahalFtp ftpUtilsInstance = null;
    private String ftpUrl;
    private int ftpPort;
    private String userName;
    private String userPassword;
    public MahalFtp(String ftpUrl, int ftpPort, String userName, String userPassword){
        this.ftpUrl = ftpUrl;
        this.ftpPort = ftpPort;
        this.userName = userName;
        this.userPassword = userPassword;
        ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(5000);//設定timeout, 預設為0, 沒有timeout, 會一直等待連線
        ftpClient.setControlEncoding("UTF-8"); //一定要放在connect之前, 不然第一次一定是亂碼
    }
    public FTPFile[] listDir(String path){
        if (!ftpClient.isConnected()){
            if (!initFtp())return null;
        }
        try {
            ftpClient.setBufferSize(1024);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            return ftpClient.listFiles(path);
        }
        catch(IOException e){
            Log.d("Thomas", "listFile error : "+e.getMessage());
        }
        return null;
    }
    public boolean chdir(String path){
        //todo
        return true;
    }
    private boolean initFtp(){
        int reply=0;
        try {
            ftpClient.connect(ftpUrl, ftpPort);
            ftpClient.login(userName, userPassword);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                return false;
            }
            return true;
        } catch (SocketException e) {
            Log.d("Thomas", "initFtp SocketException : "+e.getMessage());
        } catch (IOException e) {
            Log.d("Thomas", "initFtp IOException : "+e.getMessage());
        }
        return false;
    }
    public long uploadFile(String sourcePath, String sourceFile, String targetPath, String targetFile){
        long size=0;
        if (!initFtp()){
            return 0;
        }
        try {
            ftpClient.setBufferSize(1024);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            String[]paths=targetPath.split("/");
            for (String s :paths) {
                ftpClient.makeDirectory(s);
                ftpClient.changeWorkingDirectory(s);
            }
            BufferedInputStream bis=new BufferedInputStream(new FileInputStream(new File(sourcePath,sourceFile)));

            //檢查遠端伺服器是否有相同的文件, 有的話表示上次沒傳成功, 需先砍掉
            FTPFile[] files=ftpClient.listFiles(targetPath+"/"+targetFile);
            if(files.length==1)ftpClient.deleteFile(targetPath+"/"+targetFile);

            ftpClient.storeFile(targetFile, bis);
            bis.close();
            size=ftpClient.listFiles(targetPath+"/"+targetFile)[0].getSize();
            ftpClient.logout();
            ftpClient.disconnect();

        } catch (IOException e) {
            Log.d("Thomas", "upLoadFile error : "+e.getMessage());
        }
        return size;
    }
    public boolean downLoadFile(String FilePath, String FileName){
        if (!ftpClient.isConnected()){
            if (!initFtp()){
                return false;
            }
        }
        try {
            ftpClient.changeWorkingDirectory("./");
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.getName().equals(FileName)) {
                    File localFile = new File(FilePath);
                    OutputStream outputStream = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), outputStream);
                    outputStream.close();
                }
            }
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException e) {
            Log.d("Thomas", "downloadFile error : "+e.getMessage());
        }
        return true;
    }
}
