package kr.co.icontrols.ilp300_700.global;

import android.content.Context;
import android.util.Log;

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

import java.io.File;

import kr.co.icontrols.ilp300_700.MainActivity;
import kr.co.icontrols.ilp300_700.ethernet.iMAPServer;
import kr.co.icontrols.ilp300_700.ftp.HDCFTPManager;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.Configure.SetValue;
import kr.co.icontrols.ilp300_700.global.DataClasses.SystemUpgradeInfo;
import kr.co.icontrols.ilp300_700.global.Enumeration.UPGRADESTATUS;

public class SystemUpgrade {

    static String TAG = "SystemUpgrade";

    public static SystemUpgradeInfo FinalSystemUpgradeInfo;
    public static String MODULE_BSP = "bsp";
    public static String MODULE_APP = "app";
    public static String MODULE_ADD = "add";
    public static String MODULE_MOIP = "moip";
    public static String strUpgradeFileType_BSP = "BSP";
    public static String strUpgradeFileType_APP = "APP";
    public static String strUpgradeFileType_ADD = "ADD";
    public static String strUpgradeFileType_MOIP = "MOIP";
    public static String strUpgradeFileKeyword_ILP300_700 = "_A40i_ILP300_700_";
    public static String strUpgradeFileKeyword_ALL_ILP300_700 = "_A40i_";
    public static String strUpgradeFileKeyword_ILP300_700_6410 = "_A40i_ILP300_6410_";
    public static String strUpgradeFileKeyword_ILP300_700FR_6410 = "_A40i_ILP300FR_6410_";
    public static String strUpgradeFileExtention = "zip";
    public static String strUpgradeFileKeyword_M20 = "M20";
    public static String strUpgradeFileKeyword_M30 = "M30";

    static boolean bLOG = true;   // true, false
    static boolean bLOG_DEBUG = false;   // true, false
    static boolean bLOG_INFO = true;   // true, false
    static Context mContext;
    static HDCFTPManager mFTPManager;
    static String PATH_LOCAL_ROOT = "/sdcard/";
    static int nModuleCnt;
    String strDownloadFileName = "";

    private static void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }

    private static void LOG_DEBUG(String log) {
        if (bLOG_DEBUG) Log.d(TAG, log);
    }

    private static void LOG_INFO(String log) {
        if (bLOG_INFO) Log.i(TAG, log);
    }

    public static boolean compareFileSize(String strFileInfo, String strFileSize) {
        try {
            LOG_INFO("[compareFileSize] strFileInfo [" + strFileInfo + "], strFileSize [" + strFileSize + "]");
            File mFile = new File(strFileInfo);
            LOG_INFO("[compareFileSize] mFile.length [" + mFile.length() + "], strFileSize [" + strFileSize + "]");
            if (strFileSize.equals(Long.toString(mFile.length()))) return true;
            else return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] compareFileSize(strFileInfo, strFileSize)");
            e.printStackTrace();
            return false;
        }
    }

    public static boolean disconnectFTP() {
        try {
            if (mFTPManager.logoutFTP()) {
                if (mFTPManager.disconnectFTP()) {
                    LOG_INFO("[disconnectFTP] disconnectFTP OK!!");
                    return true;
                }
            }
            LOG_INFO("[disconnectFTP] disconnectFTP FAIL!!");
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] disconnectFTP()");
            iMAPServer.ProcSysUp = null;
            e.printStackTrace();
            return false;
        }
    }

    public static boolean cleanSDRoot() {
        try {
            LOG_INFO("[cleanSDRoot] =====START =====");
            String[] DeleteFile = null;
            DeleteFile = Global.fineDirectoryFiles(PATH_LOCAL_ROOT, strUpgradeFileKeyword_ALL_ILP300_700, strUpgradeFileExtention);

            if (DeleteFile != null) {
                LOG_INFO("[cleanSDRoot] DeleteFile.length = " + DeleteFile.length);
                File TargetFile;
                for (int i = 0; i < DeleteFile.length; i++) {
                    TargetFile = new File(PATH_LOCAL_ROOT + DeleteFile[i]);
                    if (TargetFile.delete()) {
                        LOG_INFO("[cleanSDRoot] Success to delete!! TargetFile = " + TargetFile.getName());
                    } else {
                        LOG_INFO("[cleanSDRoot] Fail to delete!! TargetFile = " + TargetFile.getName());
                    }
                }
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] cleanSDRoot()");
            e.printStackTrace();
            return false;
        }
    }

    public static boolean upgradeADDModule(String strFileName) {
        try {
            LOG_INFO("[upgradeADDModule] strFileName = " + strFileName);
            if (strFileName == "no") {
                return false;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] upgradeADDModule()");
            e.printStackTrace();
            return false;
        }
    }

    public static class ProcSystemUpgradeThread extends Thread {
        public ProcSystemUpgradeThread(Context context) {
            try {
                LOG_INFO("[ProcSystemUpgradeThread] =====START =====");
                mContext = context;
                LOG_INFO("[ProcSystemUpgradeThread] strType [" + FinalSystemUpgradeInfo.strType + "], nModuleCnt [" + FinalSystemUpgradeInfo.nModuleCnt + "], " +
                        "strUserID [" + FinalSystemUpgradeInfo.strUserID + "], strPassword [" + FinalSystemUpgradeInfo.strPassword + "]");
                for (int i = 0; i < FinalSystemUpgradeInfo.nModuleCnt; i++) {
                    LOG_INFO("[ProcSystemUpgradeThread] aModule_Type [" + i + "] = " + FinalSystemUpgradeInfo.aModule_Type[i]);
                    LOG_INFO("[ProcSystemUpgradeThread] aModule_FileName [" + i + "] = " + FinalSystemUpgradeInfo.aModule_FileName[i]);
                    LOG_INFO("[ProcSystemUpgradeThread] aModule_Path [" + i + "] = " + FinalSystemUpgradeInfo.aModule_Path[i]);
                    LOG_INFO("[ProcSystemUpgradeThread] aModule_FileSize [" + i + "] = " + FinalSystemUpgradeInfo.aModule_FileSize[i]);
                }
            } catch (Exception e) {
                Log.e(TAG, "[Exception] ProcSystemUpgradeThread(Info)");
                iMAPServer.ProcSysUp = null;
                e.printStackTrace();
            }
        }

        public void run() {
            try {
                String strRemoteFilePath = "";
                String strLocalFilePath = "";
                String strAppUpgradeFile = "no";
                String strBSPUpgradeFile = "no";
                String strAddUpgradeFile = "no";

                cleanSDRoot();   // 파일을 다운로드 하기전에 SDCard root에 있는 업그레이드 관련 파일을 모두 삭제한다. (파일명에 "_8935_"를 포함하고, 확장자가 "zip"인 파일)

                mFTPManager = new HDCFTPManager();
                if (!mFTPManager.setReceieveDataSocketBufferSize(mFTPManager.RECEIVE_BUFFERSIZE)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> setReceieveDataSocketBufferSize(" + mFTPManager.RECEIVE_BUFFERSIZE + ")");
                    iMAPServer.ProcSysUp = null;
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (!mFTPManager.setReceiveBufferSize(mFTPManager.RECEIVE_BUFFERSIZE)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> setReceiveBufferSize(" + mFTPManager.RECEIVE_BUFFERSIZE + ")");
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (!mFTPManager.connectFTP(ConfigValue.strMainServerIPAddress)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> connectFTP(" + ConfigValue.strMainServerIPAddress + ")");
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (!mFTPManager.loginFTP(FinalSystemUpgradeInfo.strUserID, FinalSystemUpgradeInfo.strPassword)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> loginFTP(" + FinalSystemUpgradeInfo.strUserID + "," + FinalSystemUpgradeInfo.strPassword + ")");
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (ConfigValue.eMainServerType != SetValue.Server2dot0_Integrated) {
                    if (!mFTPManager.setPassiveMode()) {
                        Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> setPassiveMode()");
                        disconnectFTP();
                        Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                        return;
                    }
                }

                if (!mFTPManager.setCtrlEncoding(mFTPManager.ENCODING_TYPE_EUC_KR)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> setCtrlEncoding(" + mFTPManager.ENCODING_TYPE_EUC_KR + ")");
                    disconnectFTP();
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (!mFTPManager.setFileType(FTP.BINARY_FILE_TYPE)) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> setFileType(" + FTP.BINARY_FILE_TYPE + ")");
                    disconnectFTP();
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                if (Global.getUpgradeStatus() != UPGRADESTATUS.PROPOSED) {
                    Log.w(TAG, "[ProcSystemUpgradeThread.run()] FAIL!! -> UpgradeStatus(" + Global.getUpgradeStatus() + ")");
                    disconnectFTP();
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                Global.setUpgradeStatus(UPGRADESTATUS.DOWNLOADING);

                for (int i = 0; i < FinalSystemUpgradeInfo.nModuleCnt; i++) {
                    strRemoteFilePath = FinalSystemUpgradeInfo.aModule_Path[i];
                    strLocalFilePath = PATH_LOCAL_ROOT + FinalSystemUpgradeInfo.aModule_FileName[i];
                    LOG_INFO("[ProcSystemUpgradeThread.run()] strRemoteFilePath [" + strRemoteFilePath + "], strLocalFilePath [" + strLocalFilePath + "]");
//                    DEBUG("[ProcSystemUpgradeThread.run()] SysUpInfo.aModule_Type[" + i + "] = " + SysUpInfo.aModule_Type[i]);

                    if (FinalSystemUpgradeInfo.aModule_Type[i].equalsIgnoreCase(MODULE_APP)) {
                        strAppUpgradeFile = FinalSystemUpgradeInfo.aModule_FileName[i];
                        LOG_INFO("[ProcSystemUpgradeThread.run()] strAppUpgradeFile [" + strAppUpgradeFile + "]");
                    }
                    else if (FinalSystemUpgradeInfo.aModule_Type[i].equalsIgnoreCase(MODULE_BSP)) {
                        strBSPUpgradeFile = FinalSystemUpgradeInfo.aModule_FileName[i];
                        LOG_INFO("[ProcSystemUpgradeThread.run()] strBSPUpgradeFile [" + strBSPUpgradeFile + "]");
                    }
                    else if (FinalSystemUpgradeInfo.aModule_Type[i].equalsIgnoreCase(MODULE_ADD)) {
                        strAddUpgradeFile = FinalSystemUpgradeInfo.aModule_FileName[i];
                        LOG_INFO("[ProcSystemUpgradeThread.run()] strAddUpgradeFile [" + strAddUpgradeFile + "]");
                    }

                    if (!mFTPManager.downloadFile(strRemoteFilePath, strLocalFilePath)) {
                        disconnectFTP();
                        Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                        return;
                    }

                    LOG_INFO("[ProcSystemUpgradeThread.run()] Download OK [" + strLocalFilePath + "]");

                    if (!compareFileSize(strLocalFilePath, FinalSystemUpgradeInfo.aModule_FileSize[i])) {
                        Log.e(TAG, "[ProcSystemUpgradeThread.run()] compareFileSize FAIL!!");
                        disconnectFTP();
                        Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                        return;
                    }
                }
                Global.setUpgradeStatus(UPGRADESTATUS.DOWNLOADED);

                if (!disconnectFTP()) {
                    Global.cancelSystemUpgrade(FinalSystemUpgradeInfo.aModule_Path);
                    return;
                }

                Global.setUpgradeStatus(UPGRADESTATUS.READY);

                if (upgradeADDModule(strAddUpgradeFile)) {
                    LOG_INFO("[ProcSystemUpgradeThread.run()] upgradeADDModule OK!!");
                } else {
                    LOG_INFO("[ProcSystemUpgradeThread.run()] upgradeADDModule FAIL!!");
                }

                ((MainActivity) mContext).startSystemUpgrade(strAppUpgradeFile, strBSPUpgradeFile, false);

            } catch (Exception e) {
                Log.e(TAG, "[Exception] ProcSystemUpgradeThread.run()");
                iMAPServer.ProcSysUp = null;
                e.printStackTrace();
            }
        }
    }


}