using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;

using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;

using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;

//using SystemX.Common.Protocol.SIA;

using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using SystemX.Net.Middleware.Log.Commons;
using SystemX.Net.Platform.SystemX.Common;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
using SystemX.Net.Middleware.Log.DeleteProc;
using SystemX.Net.Comm.IIS_FTP;

namespace SystemX.Net.MiddlewareUI
{
    public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
    {
        private async void WatchRecvStreamQueue()
        {
            await Task.Delay(250);

            stCheckTermBulkWaitTime.Start();
            while (!m_bTaskStreamBlock)
            {
                try
                {
                    CT.ThrowIfCancellationRequested();
                }
                catch (OperationCanceledException CancelEx)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" Work Canceled. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n" + CancelEx.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                    break;
                }
                //
                try
                {
                    if (bDatabaseConnResult == false)
                        continue;

                    if (MngDBLogConn.GetMainDBAccessTime() >= 120000)
                        QueryStreamProcess(eConnCategory.Main, "SELECT GETDATE() AS 'CHECK PING';");
                    if (MngDBLogConn.GetShortTermDBAccessTime() >= 120000)
                        QueryStreamProcess(eConnCategory.ShortTerm, "SELECT GETDATE() AS 'CHECK PING';");
                    if (MngDBLogConn.GetLongTermDBAccessTime() >= 120000)
                        QueryStreamProcess(eConnCategory.LongTerm, "SELECT GETDATE() AS 'CHECK PING';");

                    nBulkLogCount = lstBulkTermLogInfo.Count;
                    nBulkLongTermCount = lstBulkShortTermLog.Count;
                    nBulkShortTermCount = lstBulkLongTermLog.Count;
                    nBulkTimeValue = stCheckTermBulkWaitTime.ElapsedMilliseconds;

                    if (stCheckTermBulkWaitTime.ElapsedMilliseconds >= LoadInfo.BULK_ProcessTime_ms || bTryBulkInsertBuffer)
                    {
                        Stopwatch stMeasProcTime = new Stopwatch();

                        if (lstBulkTermLogInfo.Count > 0)
                        {
                            stMeasProcTime.Start();

                            foreach (string str in lstBulkTermLogInfo.ToArray())
                            {
                                LogDataRecvText.Enqueue(new StringBuilder(str));
                                LogDataRecvText.Enqueue(new StringBuilder("\r\n"));
                            }

                            lstBulkTermLogInfo.Clear();
                        }
                        //
                        if(lstBulkShortTermLog.Count > 0)
                            SetLogDataInsertProc(eConnCategory.ShortTerm);
                        if (lstBulkLongTermLog.Count > 0)
                            SetLogDataInsertProc(eConnCategory.LongTerm);

                        BULK_INSERT_EXIT:

                        if (stMeasProcTime.IsRunning)
                        {
                            LogDataRecvText.Enqueue(new StringBuilder(">>[BulkInsert-Process][" + stMeasProcTime.ElapsedMilliseconds.ToString() + "]\r\n"));

                            //Check Server Time And Db Change
                            bDatabaseConnResult = MngDBLogConn.CheckDatabaseConnection();
                        }

                        bTryBulkInsertBuffer = false;

                        stCheckTermBulkWaitTime.Restart();
                    }

                    //Map Log File Check
                    if (bTaskStreamWaitLock == false)
                        QueryRecvStreamQueue();

                    // TODO : FTP ALIS
                    if (StateFTP != eFTPServiceStatus.Connected)
                        goto ROUTINE_END;

                    //FTP Server Check
                    nFTPTimeValue = stProcessCheckFTPTime.ElapsedMilliseconds;

                    if (stProcessCheckFTPTime.ElapsedMilliseconds >= LoadInfo.FTP_ScanTime_ms)
                    {
                        List<string> lstFile = ControlFTP.PositionRootCheckList();

                        List<string> lstDownlaodFile = new List<string>();
                        List<string> lstDeleteFailedFile = new List<string>();

                        if (lstFile.Count == 0)
                            goto BRANCH_EXIT;

                        string strGetDownloadPath = GetFTPDownloadPath();

                        foreach (string f in lstFile)
                            lstDownlaodFile.Add(await ControlFTP.FileDownload(f, strGetDownloadPath));

                        foreach (string f in lstDownlaodFile)
                        {
                            string strGetFileName = Path.GetFileName(f);

                            if (ControlFTP.DeleteFile(strGetFileName) == false)
                                lstDeleteFailedFile.Add(strGetFileName);
                        }

                        BRANCH_EXIT:

                        ProcFTPCheckLogFiles();

                        foreach (string f in lstDeleteFailedFile)
                        {
                            string strGetFileName = Path.GetFileName(f);

                            if (ControlFTP.DeleteFile(strGetFileName) == false)
                            {
                                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"FTP > file delete process failed. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                            }
                        }

                        stProcessCheckFTPTime.Restart();
                    }

                    ROUTINE_END:;
                }
                catch (Exception e)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"General Queue Process failed. [SystemX.Net.MiddlewareUI : MainForm.WatchRecvStreamQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }

                await Task.Delay(100);
            }
        }

        private void SetLogDataInsertProc(eConnCategory SetCategory)
        {
            bool bBulkCopyResult = true;

            string strSetLogTable = string.Empty;
            string strAddText = string.Empty;

            if (SetCategory == eConnCategory.ShortTerm)
            {
                strSetLogTable = MngDBLogConn.GetDBConnectInfo().ConnShortTerm.LOG_TABLE;
                strAddText = "ShortTerm";
            }
            else if (SetCategory == eConnCategory.LongTerm)
            {
                strSetLogTable = MngDBLogConn.GetDBConnectInfo().ConnLongTerm.LOG_TABLE;
                strAddText = "LongTerm";
            }

            try
            {
                //LogData Set Bulk
                using (SqlTransaction sqlTran = MngDBLogConn.CurrentConnection(SetCategory).getConnection().BeginTransaction())
                {
                    //Sql Bulk Insert 준비 - Short Log
                    //Make Result Command
                    SqlBulkCopy sbc = new SqlBulkCopy(sqlTran.Connection,
                               SqlBulkCopyOptions.CheckConstraints |
                               SqlBulkCopyOptions.FireTriggers |
                               SqlBulkCopyOptions.KeepNulls, sqlTran);
                    sbc.BatchSize = 5000;
                    sbc.DestinationTableName = "dbo." + strSetLogTable;
                    sbc.BulkCopyTimeout = 120;

                    try
                    {
                        // Write from the source to the destination.
                        //생성된 DataRow 들을 Bulk Copy 실시
                        if (SetCategory == eConnCategory.ShortTerm)
                            sbc.WriteToServer(lstBulkShortTermLog.ToArray());
                        else if (SetCategory == eConnCategory.LongTerm)
                            sbc.WriteToServer(lstBulkLongTermLog.ToArray());

                        //if (MngDBConn.InfoConnection.UTSI_STATE)
                        //{
                        //    //Long Log
                        //    SqlBulkCopy sbcL = new SqlBulkCopy(sqlTran.Connection,
                        //               SqlBulkCopyOptions.CheckConstraints |
                        //               SqlBulkCopyOptions.FireTriggers |
                        //               SqlBulkCopyOptions.KeepNulls, sqlTran);
                        //    sbcL.BatchSize = 5000;
                        //    sbcL.DestinationTableName = "dbo.HIST_TestResultLongTerm";
                        //    sbcL.BulkCopyTimeout = 120;
                        //
                        //    sbcL.WriteToServer(SetMakeLogRows);
                        //}
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + $@" CPXV2 CpLogProcess fail.({strAddText} - Bulk Upload) [SystemX.Net.MiddlewareUI : MainForm.SetLogDataInsertProc]\r\n" + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);

                        bBulkCopyResult = false;
                    }
                    finally
                    {
                        // Close the SqlDataReader. The SqlBulkCopy
                        // object is automatically closed at the end
                        // of the using block.
                        if (bBulkCopyResult)
                        {
                            sqlTran.Commit();

                            if (SetCategory == eConnCategory.ShortTerm)
                                lstBulkShortTermLog.Clear();
                            else if (SetCategory == eConnCategory.LongTerm)
                                lstBulkLongTermLog.Clear();

                            LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - All CpLogs(Bulk)Process Result [OK]>\r\n"));
                        }
                        else
                        {
                            sqlTran.Rollback();

                            LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - All CpLogs(Bulk)Process Result [NOK]>\r\n"));

                            //throw new Exception();
                        }
                    }
                }
            }
            catch
            {
                ;//
            }
            finally
            {
                ;//
            }

            if (bBulkCopyResult == false)
            {
                CommonProtocol cp = new CommonProtocol();

                List<DataRow> lstRefRow = null;

                if (SetCategory == eConnCategory.ShortTerm)
                    lstRefRow = lstBulkShortTermLog;
                else if (SetCategory == eConnCategory.LongTerm)
                    lstRefRow = lstBulkLongTermLog;

                foreach (DataRow dr in lstRefRow)
                {
                    if (Convert.ToInt64(dr["No"]) == Int64.MinValue)
                        continue;

                    //Summary 객체를 이용해 DB 삽입할 SqlCommand 생성
                    SqlCommand cmd = cp.LogDataResultInsert(strSetLogTable, dr);

                    //Summary 삽입 > 실패시 처리 
                    bool bProcessResult = ExcuteNonQueryStreamProcess(SetCategory, cmd);

                    if (bProcessResult == false)
                    {
                        LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - CpLogs(Command) Process Result [NOK]>\r\n"));

                        continue;
                    }
                    else
                        LogDataRecvText.Enqueue(new StringBuilder($"<{strAddText} - CpLogs(Command) Process Result [OK]>\r\n"));
                }

                if (SetCategory == eConnCategory.ShortTerm)
                    lstBulkShortTermLog.Clear();
                else if (SetCategory == eConnCategory.LongTerm)
                    lstBulkLongTermLog.Clear();
            }
        }

        private bool QueryRecvStreamQueue()
        {
            //StackTrace st = new StackTrace(true);

            bool bState = true;

            string strProcessDebugInfo = string.Empty;

            long l1 = long.MinValue;
            long l2 = long.MinValue;

            try
            {
                bTaskStreamWaitLock = true;

                //Log Process
                Stopwatch stProcessTimeChk = new Stopwatch();
                stProcessTimeChk.Start();

                for (int i = PORT_DISTRIBUTION_NUM; i < ALL_MANAGE_NUM && !m_bTaskCommandBlock; i++)
                {
                    Stopwatch stItemTimeChk = new Stopwatch();
                    stItemTimeChk.Start();

                    if (LogDataQueue[i].Count <= 0)
                        continue;

                    LogMappedPacket LogMapFile = new LogMappedPacket();
                    int nSetSize = Marshal.SizeOf(LogMapFile);
                    byte[] ucSetLogArray = new byte[nSetSize];
                    LogMapFile = (LogMappedPacket)SystemXNetSerialization.RawDeSerialize(ucSetLogArray, LogMapFile.GetType());

                    int iPos = LogMapFile.nNumber;
                    strProcessDebugInfo = "[" + (iPos).ToString("D2") + "]" +
                        "[" + LogMapFile.nCommandPort + "]" +
                        "[" + LogMapFile.objHost[0].Data + "]" +
                        "[" + LogMapFile.objSection[0].Data + "]";
                    //
                    if (LogDataQueue[i].TryPeek(out LogMapFile)) //LogDataQueue[i].TryDequeue(out LogMapFile))
                    {
                        if (bShowCpLogProcessTime)
                            LogMapFile.bShowCpLogProcessTime = true;

                        StringBuilder sb = new StringBuilder();
                        sb.Append("[" + (++nDequeueCount).ToString() + "][TryDequeue]");
                        sb.Append("[");
                        sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                        sb.Append("], ");
                        sb.Append("Type [" + LogMapFile.objLogType[0].Data.ToString() + "], ");
                        sb.Append("S Port [" + LogMapFile.nStreamPort.ToString() + "], ");
                        sb.Append("C Port [" + LogMapFile.nCommandPort.ToString() + "], ");
                        sb.Append("Size [" + LogMapFile.nLogDataSize.ToString() + "], ");
                        sb.Append("Number [" + LogMapFile.nNumber.ToString() + "], ");
                        sb.Append("Host [" + LogMapFile.objHost[0].Data + "], ");
                        sb.Append("Section [" + LogMapFile.objSection[0].Data + "], ");
                        sb.Append("St Name [" + LogMapFile.objStationName[0].Data + "], ");
                        sb.Append("St ID [" + LogMapFile.nStationID.ToString() + "], ");
                        sb.Append("File Name [" + LogMapFile.objOptionFileName[0].Data + "], ");
                        sb.Append("File Extension [" + LogMapFile.objOptionFileExtension[0].Data + "] ");
                        sb.Append("TL ID[" + LogMapFile.objResultTestListCntID[0].Data + "], ");
                        sb.Append("V[" + LogMapFile.objProdPNo[0].Data + "], ");
                        sb.Append("PN[" + LogMapFile.objProdCNo[0].Data + "], ");
                        sb.Append("TT[" + LogMapFile.objTestType[0].Data + "], ");
                        sb.Append("TC[" + LogMapFile.objTestCode[0].Data + "], ");
                        sb.Append("Ver[" + LogMapFile.objVersion[0].Data + "], ");
                        sb.Append("PC[" + LogMapFile.objProdCode[0].Data + "], ");
                        sb.Append("DB V No[" + LogMapFile.nTestListVariantNo.ToString() + "], ");

                        if (nDequeueCount >= Int64.MaxValue)
                            nDequeueCount = 0;

                        bool bProcResult = false;

                        if (MngDBLogConn.GetDBConnectInfo().ConnVersion == XDBConnInfo.eVersion.CPX)
                        {
                            sb.Append("!Use Log Process Version [CPX] - No longer supported.");

                            //bProcResult = CPX_CpLogProcess(LogMapFile);

                            bProcResult = false;
                        }
                        else if (MngDBLogConn.GetDBConnectInfo().ConnVersion == XDBConnInfo.eVersion.CPXV2)
                        {
                            bProcResult = CPXV2_CpLogProcess(LogMapFile);

                            if(bProcResult == true)
                                lstBulkTermLogInfo.Add(sb.ToString());

                            sb.Append("!Use Log Process Version [CPXV2] ");
                        }

                        if (bProcResult)
                            sb.Append("<CpLogProcess Make Log Result [OK]>");
                        else
                            sb.Append("<CpLogProcess Make Log Result [NOK]>");

                        sb.AppendLine();

                        LogDataProcessText.Enqueue(sb);

                        if (LogDataQueue[i].TryDequeue(out LogMapFile) == false)
                        {
                            if (LogDataQueue[i].TryDequeue(out LogMapFile) == false)
                            {
                                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo + @" Recv queue try-dequeue failed. [SystemX.Net.MiddlewareUI : MainForm.QueryRecvStreamQueue]\r\n", ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                            }
                        }
                    }

                    l2 = stItemTimeChk.ElapsedMilliseconds;
                }

                l1 = stProcessTimeChk.ElapsedMilliseconds;

                if (l1 != long.MinValue && l2 != long.MinValue)
                {
                    LogDataProcessText.Enqueue(new StringBuilder(">>[TryDequeue-Process][" + l1.ToString() + "][TryDequeue-Item][" + l2.ToString() + "]\r\n"));
                }
            }
            catch (Exception e)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo + @" Recv queue stream process unknown fail. [SystemX.Net.MiddlewareUI : MainForm.QueryRecvStreamQueue]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                bState = false;
            }
            finally
            {
                bTaskStreamWaitLock = false;
            }

            return bState;
        }

        // TODO : FTP ALIS
        internal eFTPServiceStatus StartFTPService()
        {
            ControlFTP = new CtrlFTP(LoadInfo.FTP_Use,
                IPAddress.Parse(LoadInfo.FTP_IPAddress), Convert.ToInt32(LoadInfo.FTP_Port),
                LoadInfo.FTP_Account, LoadInfo.FTP_Password);

            if (ControlFTP.FTPConnState)
                return eFTPServiceStatus.Connected;
            else
                return eFTPServiceStatus.Disconnected;
        }

        private string GetFTPDownloadPath()
        {
            string strYYYY = DateTime.Today.ToString("yyyy");
            string strMM = DateTime.Today.ToString("MM");
            string strdd = DateTime.Today.ToString("dd");

            string strHHmmssfff = DateTime.Now.ToString("HHmmssfff");
            string strGetRoot = Path.GetPathRoot(Environment.CurrentDirectory);
            string DirPath = @strGetRoot + $@"\XProc\FTP\CpLog\{strYYYY}\{strMM}\{strdd}\";

            //string CpLogDirPath = @strGetRoot + $@"XProcCpLog\Temp\{strYYYY}\{strMM}\{strdd}\{strHHmmssfff}\";

            DirectoryInfo di1 = new DirectoryInfo(@DirPath);
            if (!di1.Exists) Directory.CreateDirectory(@DirPath);

            //DirectoryInfo di2 = new DirectoryInfo(@CpLogDirPath);
            //if (!di2.Exists) Directory.CreateDirectory(@CpLogDirPath);

            return DirPath;
        }

        private void ProcFTPCheckLogFiles()
        {
            //Scan And Send File
            string strGetRoot = Path.GetPathRoot(Environment.CurrentDirectory);

            //오늘 포함 -6일전까지 검색
            string[] strScanYYYY = new string[7];
            string[] strScanMM = new string[7];
            string[] strScandd = new string[7];

            for (int n = 6; n >= 0; n--)
            {
                DateTime dtSet = DateTime.Today.AddDays(-n);
                strScanYYYY[n] = dtSet.ToString("yyyy");
                strScanMM[n] = dtSet.ToString("MM");
                strScandd[n] = dtSet.ToString("dd");
            }
            //
            // 7일치 위치 확인
            // 
            for (int n = 0; n < 7; n++)
            {
                string DirPath = strGetRoot + $@"\XProc\FTP\CpLog\{strScanYYYY[n]}\{strScanMM[n]}\{strScandd[n]}\";
                string DirMovePath = strGetRoot + $@"\XProc\FTP\CpLog\{strScanYYYY[n]}\{strScanMM[n]}\{strScandd[n]}\History\";

                //생성 폴더가 없을경우 SKIP
                if (Directory.Exists(DirPath) == false)
                    continue;

                if (Directory.Exists(DirMovePath) == false)
                    Directory.CreateDirectory(DirMovePath);

                string fileExtension = "zip";

                string[] dirs = Directory.GetDirectories(DirPath);
                string[] files = Directory.GetFiles(DirPath, $"*.{fileExtension}", SearchOption.TopDirectoryOnly);

                if (files.Length <= 0)
                    continue;

                ProcFTPLogFiles(files, DirPath, DirMovePath);
            }
        }

        private void ProcFTPLogFiles(string[] strArrFiles, string strReadDirPath, string strMoveDirPath)
        {
            string strExtractFilePos = string.Empty;
            string strOrgRemoveFilePos = string.Empty;

            string strHeaderInfo = string.Empty;
            string strLogFileNameInfo = string.Empty;

            long l1 = long.MinValue;

            //Log Process
            Stopwatch stProcessTimeChk = new Stopwatch();
            stProcessTimeChk.Start();

            foreach (string f in strArrFiles)
            {
                strOrgRemoveFilePos = f;

                strHeaderInfo = string.Empty;
                strLogFileNameInfo = string.Empty;

                string[] strInfos = f.Split(';');

                //파일정보 확인(로그 저장관련 정보)
                /*
                string strSetDateTime = strInfos[1];
                string strSetStationName = strInfos[2];
                int nSetTestListVariantNo = int.Parse(strInfos[3]);
                string strSetProcNoP = strInfos[4];
                string strSetProcNoC = strInfos[5];
                string strSetTestType = strInfos[6];
                string strSetTestCode = strInfos[7];
                string strSetVersion = strInfos[8];
                string strSetProdCode = strInfos[9];
                string strSetTestListCntID = strInfos[10];
                string strHost = strInfos[11];
                string strSection = strInfos[12];
                */
                int nSetTryNo = int.Parse(strInfos[13]);

                Dictionary<string, string> dicSetLogInfo = new Dictionary<string, string>();
                dicSetLogInfo.Add("DATE_TIME", strInfos[1]);
                dicSetLogInfo.Add("STATION_NAME", strInfos[2]);
                dicSetLogInfo.Add("VARIANT_NO", strInfos[3]);
                dicSetLogInfo.Add("P_TTNR", strInfos[4]);
                dicSetLogInfo.Add("TTNR", strInfos[5]);
                dicSetLogInfo.Add("TEST_TYPE", strInfos[6]);
                dicSetLogInfo.Add("TEST_CODE", strInfos[7]);
                dicSetLogInfo.Add("VERSION", strInfos[8]);
                dicSetLogInfo.Add("PROD_CODE", strInfos[9]);
                dicSetLogInfo.Add("TESTLIST_ID", strInfos[10]);
                dicSetLogInfo.Add("HOST", strInfos[11]);
                dicSetLogInfo.Add("SECTION", strInfos[12]);

                for (int m = 1; m < 12; m++)
                    strHeaderInfo += (strInfos[m + 1] + ";");

                strHeaderInfo = strHeaderInfo.Remove(strHeaderInfo.Length - 1, 1);

                //압축해제 하여 로그 파일 추출         
                using (FileStream fs = new FileStream(f, FileMode.Open))
                using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Update, false))
                {
                    foreach (ZipArchiveEntry zae in zip.Entries)
                    {
                        strLogFileNameInfo = zae.FullName;

                        if (strLogFileNameInfo.IndexOf(".txt") >= 0)
                            continue;

                        strExtractFilePos = strReadDirPath + strLogFileNameInfo;

                        //ZipFileExtensions
                        zae.ExtractToFile(strExtractFilePos, true);
                    }
                }

                //Sometihing Procee
                LogMappedPacket EmptyLogMapFile = new LogMappedPacket();

                StringBuilder sb = new StringBuilder();
                sb.Append("[" + (++nDequeueCount).ToString() + "][TryDequeue]");
                sb.Append("[");
                sb.Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                sb.Append("], ");
                sb.Append("Type [FTP], ");
                sb.Append("Host [" + dicSetLogInfo["HOST"] + "], ");
                sb.Append("Section [" + dicSetLogInfo["SECTION"] + "], ");
                sb.Append("St Name [" + dicSetLogInfo["STATION_NAME"] + "], ");
                sb.Append("File Name [" + Path.GetFileName(strExtractFilePos) + "], ");
                sb.Append("File Extension [" + Path.GetExtension(strExtractFilePos) + "] ");
                sb.Append("TL ID[" + dicSetLogInfo["TESTLIST_ID"] + "], ");
                sb.Append("V[" + dicSetLogInfo["P_TTNR"] + "], ");
                sb.Append("PN[" + dicSetLogInfo["TTNR"] + "], ");
                sb.Append("TT[" + dicSetLogInfo["TEST_TYPE"] + "], ");
                sb.Append("TC[" + dicSetLogInfo["TEST_CODE"] + "], ");
                sb.Append("Ver[" + dicSetLogInfo["VERSION"] + "], ");
                sb.Append("PC[" + dicSetLogInfo["PROD_CODE"] + "], ");
                sb.Append("DB V No[" + dicSetLogInfo["VARIANT_NO"] + "], ");

                if (nDequeueCount >= Int64.MaxValue)
                    nDequeueCount = 0;

                bool bGetLogProcResult = CPXV2_CpLogProcess(EmptyLogMapFile, dicSetLogInfo, strExtractFilePos);

                if (bGetLogProcResult == true)
                    lstBulkTermLogInfo.Add(sb.ToString());

                sb.Append("!Use Log Process Version [FTP-CPXV2] ");

                if (bGetLogProcResult)
                    sb.Append("<CpLogProcess Make Log Result [OK]>");
                else
                    sb.Append("<CpLogProcess Make Log Result [NOK]>");

                sb.AppendLine();

                LogDataProcessText.Enqueue(sb);

                l1 = stProcessTimeChk.ElapsedMilliseconds;

                if (l1 != long.MinValue)
                {
                    LogDataProcessText.Enqueue(new StringBuilder(">>[FTP-Process][" + l1.ToString() + "]\r\n"));
                }

                //Failed
                if (bGetLogProcResult == false)
                {
                    //실패시 
                    nSetTryNo++;

                    string strTryNo = string.Empty;

                    string strCopyPos = string.Empty;

                    //재시도 3회 초과 일시 히스토리로 이동 
                    if (nSetTryNo > 3)
                    {
                        strCopyPos = strMoveDirPath;

                        strTryNo = "X";
                    }
                    else
                    {
                        strCopyPos = strReadDirPath;

                        strTryNo = nSetTryNo.ToString();
                    }

                    for (int m = 0; m < 12; m++)
                        strCopyPos += (";" + strInfos[m + 1]);

                    strCopyPos += (";" + strTryNo + ";.zip");

                    File.Copy(f, strCopyPos, true);
                }

                //압축해제 파일 삭제
                if (File.Exists(strExtractFilePos))
                    File.Delete(strExtractFilePos);

                //성공시나 실패시 새로운 파일생성 되기 때문에 기존 파일 삭제
                if (strOrgRemoveFilePos != string.Empty)
                {
                    if (File.Exists(strOrgRemoveFilePos))
                        File.Delete(strOrgRemoveFilePos);
                }

                stProcessTimeChk.Restart();
            }
        }
    }
}
