package kr.co.icontrols.ilp300_700.ftp;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.artncore.WallPadDataMgr.WallpadDeviceSet;
import com.artncore.WallPadDataMgr.WallpadStatusData;

import org.apache.commons.net.ftp.FTP;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ftp_FileDownload{
    String ftpPATH;
    Handler handle;
    int Index;
    //FTPClient f;
    HDCSFTPManager f;
    //ftp_FileDownloadWatcher WatchThread;
    String localFile;
    String TAG = "ftp_FileDownload";
    boolean CompleteFlag = true; //event_notify 계속보내는 버그로 인하여 추가함

    String m_strIP="", m_strID="", m_strPWD="", m_strPATH="", m_strFileName="", m_strName="";

    public ftp_FileDownload(String strIP, String strID, String strPWD, String strPATH, String strFileName, String strName) {
        m_strIP = strIP;
        m_strID = strID;
        m_strPWD = strPWD;
        m_strPATH = strPATH;
        m_strFileName = strFileName;
        m_strName = strName;

    }

//    public ftp_FileDownload(Handler handle, String path, int idx, String LocalFileName) {
//        ftpPATH     = path;
//        Index       = idx;
//        this.handle = handle;
//        //WatchThread = wat;
//        localFile = LocalFileName;
//    }

    public boolean run() {
        //Log.d(TAG,  "[ftp_FileDownload.run()] ftp_FileDownload start! " + ftpPATH + "]");
        //f = new FTPClient();
        Log.d("", "업데이트 파일 다운로드 시작");
        f = new HDCSFTPManager();
        //f.setControlEncoding("euc-kr"); //한글이름의 파일은 FTP 다운로드가 안되기 때문에 인코딩 추가로 넣어줌
        f.setCtrlEncoding("UTF-8"); //한글이름의 파일은 FTP 다운로드가 안되기 때문에 인코딩 추가로 넣어줌
        Log.d(TAG, "[ftp_FileDownload.run()] setCtrlEncodingt! ]");
        f.setReceieveDataSocketBufferSize(1024*512);
        try {
            f.setReceiveBufferSize(1024*512);
        }
        catch (RuntimeException re)
        {
            Log.d(TAG, "setReceiveBufferSize" + re.toString());
            Log.e(TAG, ""+re);
            ProcDownFail();
            return false;
        }
        catch (Exception e1) {
            //e1.printStackTrace();
            //Log.d(TAG, "setReceiveBufferSize" + e1.toString());
            Log.e(TAG, ""+e1);
            //RetryHandler.sendEmptyMessageDelayed(0, retryDelay);
            ProcDownFail();
            return false;
        }

        int recebf = f.getReceiveDataSocketBufferSize();
        Log.d(TAG, "[ftp_FileDownload.run()] getReceiveDataSocketBufferSize! ]");
        FileOutputStream fos = null;
        BufferedOutputStream ffos = null;
        try {

            boolean ret = false;
            ret = f.connectFTP(m_strIP);
            if (ret == false) {
                //Log.d(TAG, "loginFTP False, ID : " + id + ", PW : " + passwd);
                ProcDownFail();
                return false;
            }
            Log.d(TAG, "[ftp_FileDownload.run()] connectFTP! ]");

            Log.d(TAG, "[ftp_FileDownload.run()] Login Try ]");
            for(int i =0; i< 1; i++)
                ret = f.loginFTP(m_strID, m_strPWD);

            if (ret == false) {
                //Log.d(TAG, "loginFTP False, ID : " + id + ", PW : " + passwd);
                ProcDownFail();
                return false;
            }


            if (true) {
                if (!f.setPassiveMode()) {
                    Log.d(TAG, "[uploadVisitorPicture.run()] FAIL!! -> setPassiveMode(...)");
                    try {
                        if (f.logoutFTP()) {
                            if (f.disconnectFTP()) {
                                Log.d(TAG, "[disconnectFTP] disconnectFTP OK!!");
                            }
                        }
                        Log.d(TAG, "[disconnectFTP] disconnectFTP FAIL!!");
                    } catch (RuntimeException re) {
                        Log.e(TAG, ""+re);
                    }
                    catch (Exception e) {
                        Log.d(TAG,  "[Exception] disconnectFTP()");
                        //e.printStackTrace();
                        Log.e(TAG, ""+e);
                    }
                    Log.d(TAG,  "-" +"setPassiveMode False");
                    ProcDownFail();
                }
            }

            //Log.d(TAG, "[ftp_FileDownload] path [" + path+ "], localFile [" + localFile+ "]");

            ret = f.changeWorkingDirectory(m_strPATH);
            if (ret == false) {
                Log.d(TAG, "changeWorkingDirectory False");
                ProcDownFail();
                return false;
            }

            ret = f.setFileType(FTP.BINARY_FILE_TYPE);
            if (ret == false) {
                Log.d(TAG, "setFileType False");
                ProcDownFail();
                return false;
            }

            Log.d(TAG, "setFileType 1");

            File downloadfile = new File(m_strName);
            if (downloadfile.exists()) downloadfile.delete();//.delete();
            fos = new FileOutputStream(downloadfile);
            ffos = new BufferedOutputStream(fos);

            Log.d(TAG, "setFileType 2");
//            path = ftpPATH;
            boolean result;
            ///"modules/app/APP_V40_IHND101_2021031602.zip"

            result = f.retrieveFile(m_strFileName, ffos);
            ffos.flush();

            Log.d(TAG, "setFileType 3");
            if (result == false) {
                String error = f.getError();

                Log.d(TAG, "retrieveFile Fail path : " + m_strFileName  + ", Error : " + error);
                ProcDownFail();
                return false;
            }

            //if (handle == null) Log.d(TAG, "[ftp_FileDownload.run()] handle is null!!");
            //else Log.d(TAG, "[ftp_FileDownload.run()] handle is not null!!");
            Log.d(TAG, "[ftp_FileDownload.run()] CompleteFlag [" + CompleteFlag+ "]");
            //if ((handle != null) && (CompleteFlag == true)) {
            if(CompleteFlag == true)
            {
                Log.d("", "업데이트 파일 다운로드 완료");
                return true;
//                // event_notify 계속보내는 버그로 인하여 추가함
//                Message msg = handle.obtainMessage();
//                msg.what = DOWNLOAD_SUCCESS_MSG;
//                msg.arg1 = (result) ? 1 : 0;
//                msg.arg2 = Index;
//                msg.obj = localFile;
//                handle.sendMessage(msg);
            }
            Log.d(TAG, "setFileType 5");
            //WatchThread.onoff = false;
        } catch (RuntimeException re) {
            Log.d(TAG, re.toString());
            Log.e(TAG, ""+re);
            ProcDownFail();
        }
        catch (Exception e) {
            Log.e(TAG, "[Exception] ftp_FileDownload.run() 1");
            //Log.d(TAG, "[Exception] ftp_FileDownload.run() 1");
            //Log.d(TAG, e.toString());
            //e.printStackTrace();
            Log.e(TAG, ""+e);
            ProcDownFail();
            return false;
        }
        finally {
            if(fos!=null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    Log.e(TAG, ""+e);
                }
            }
            fos = null;

            if(ffos!=null) {
                try {
                    ffos.close();
                } catch (IOException e) {
                    Log.e(TAG, ""+e);
                }
                ffos = null;
            }
        }

        try{
            f.quit();
        } catch (RuntimeException re) {
            Log.e(TAG, ""+re);
        }
        catch (Exception e) {
            Log.e(TAG, "[Exception] ftp_FileDownload.run() 2");
            //e.printStackTrace();
            Log.e(TAG, ""+e);
        }

        return true;
    }

    private void ProcDownFail() {
        try {
            Log.d(TAG, "[ProcDownFail] ========== Download failed ==========");
            CompleteFlag = false; //event_notify 계속보내는 버그로 인하여 추가함
            f.logout();
            f.quit();
        } catch (RuntimeException re) {
            Log.e(TAG, ""+re);
        }
        catch (Exception e) {
            //e.printStackTrace();
            Log.e(TAG, ""+e);
        }
        //WatchThread.onoff = false;
//
//        Message msg = handle.obtainMessage();
//        msg.what = DOWNLOAD_FAIL_MSG;
//        msg.arg1 = 0;
//        msg.arg2 = Index;
//        msg.obj = ftpPATH;
//        handle.sendMessage(msg);
    }
}
