using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using DDUtilityApp.DATA;
using DDUtilityApp.LOGPARSER.DATA;
using DDUtilityApp.LOGPARSER.PARSER;
using DDUtilityApp.MONGO;
using DDUtilityApp.SECS;
using FluentFTP;
using JWH;
using JWH.CONTROL;
using JWH.NETWORK;
using Telerik.WinControls.UI;
using ContentAlignment = System.Drawing.ContentAlignment;

namespace DDUtilityApp.LOGPARSER
{

    public partial class FrmLogParser : Form
    {

        #region [ Variable ] --------------------------------------------------

        private LogParser m_LogParser = null;

        private FrmMessageReplyTime1 FrmMessageReplyTime { get; set; } = null;

        private bool IsLogFolderOpen { get; set; } = false;

        #endregion

        #region [ Properties ] ------------------------------------------------

        private bool RadGridControlKey { get; set; } = false;

        private StandardCollection StandardCollection { get; set; } = new StandardCollection();

        public LogParser LogParser
        {
            get { return this.m_LogParser; }
            set { this.SetLogParser(value); }
        }

        private void SetLogParser(LogParser parser)
        {
            this.m_LogParser = parser;
            if (parser == null) return;

            this.LogParser.SetGridHeader(this.grid);
        }

        public EisEquipment Equipment { get; set; } = null;

        public SECSDefine SECSDefine { get; set; } = null;

        private FrmFindDialog FindDialog { get; set; } = null;

        private string WindowText { get; set; } = $"[EverOne] EIS Log Viewer";

        private string ServerName { get; set; } = string.Empty;

        private string EquipmentID { get; set; } = string.Empty;

        #endregion

        #region [ FrmLogParser ] ----------------------------------------------

        public FrmLogParser()
        {
            InitializeComponent();
            this.SetLayout();
            this.SetEventHandler();

            XLogger.Instance.Control = this.tboxException;
        }

        public FrmLogParser(LogParser parser, string serverName, string equipmentID) : this()
        {
            this.LogParser = parser;
            if (parser == null) return;

            this.ServerName = serverName;
            this.EquipmentID = equipmentID;
        }

        private void SetLayout()
        {
            this.AllowDrop = true;
#if DEBUG
            this.Text = $"{this.WindowText} - Ver. {Application.ProductVersion} : DEBUG";
#else
            this.Text = $"{this.WindowText} - Ver. {Application.ProductVersion}";
#endif
            Font font = new Font("돋움체", 9);

            this.tboxLog.AllowDrop = true;
            this.tboxLog.WordWrap = false;
            this.tboxLog.Multiline = true;
            this.tboxLog.HideSelection = false;
            this.tboxLog.ScrollBars = ScrollBars.Both;
            this.tboxLog.Font = font;
            this.tboxLog.SetTabWidth(4);

            this.tboxException.WordWrap = false;
            this.tboxException.Font = font;
            this.tboxException.SetTabWidth(4);

            this.lviewFiles.View = View.Details;
            ColumnHeader header = this.lviewFiles.Columns.Add("File Name");
            header = this.lviewFiles.Columns.Add("Size");
            header.TextAlign = HorizontalAlignment.Right;
            this.lviewFiles.CheckBoxes = true;
            this.lviewFiles.MultiSelect = false;
            this.lviewFiles.GridLines = true;
            this.lviewFiles.FullRowSelect = true;
            this.lviewFiles.Sorting = System.Windows.Forms.SortOrder.Ascending;
            this.lviewFiles.HeaderStyle = ColumnHeaderStyle.Nonclickable;
            this.lviewFiles.ListViewItemSorter = new ListViewItemComparer(0, this.lviewFiles.Sorting);

            this.chkAutoClear.Checked = true;
            this.chkDownload.Checked = true;
            this.chkShowGroupColumns.Checked = true;
            this.chkLogSynchronization.Checked = true;
            this.chkHideLinktest.Checked = true;
            this.chkHidTID.Checked = true;
            this.chkHideTraceData.Checked = true;
            this.btnOpenWorkFlow.Visible = false;
            this.chkGridDTGroupKey.Items.Clear();
            foreach (GridViewEx.eDateTimeGroupKey key in Enum.GetValues(typeof(GridViewEx.eDateTimeGroupKey)))
            {
                if (key == GridViewEx.eDateTimeGroupKey.Date) continue;

                bool check = false;
                if ((key & GridViewEx.eDateTimeGroupKey.Date) > 0) check = true;
                RadCheckedListDataItem item = new RadCheckedListDataItem(key.ToString(), check);
                item.Value = key;
                this.chkGridDTGroupKey.Items.Add(item);
            }
#if !DEBUG
            this.btnTest01.Visible = false;
#endif

            this.RadGrid_Setting();
            this.ActiveControl = this.btnEqpSelector;

            this.cboxLineNumber.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cboxLineNumber.Font = font;
            this.cboxLineNumber.DisplayMember = "Key";
            this.cboxLineNumber.ValueMember = "Value";
            this.cboxLineNumber.Sorted = true;
        }

        private void SetEventHandler()
        {
            // DragDrop
            this.DragDrop += Control_DragDrop;
            this.DragEnter += Control_DragEnter;
            this.Load += FrmLogParser_Load;
            this.FormClosing += FrmLogParser_FormClosing;

            this.tboxLog.DragDrop += Control_DragDrop;
            this.tboxLog.DragEnter += Control_DragEnter;
            this.tboxLog.KeyDown += TboxLog_KeyDown;

            // File List
            this.lviewFiles.Click += LviewFiles_Click;
            this.lviewFiles.ColumnClick += LviewFiles_ColumnClick;
            this.lviewFiles.Resize += LviewFiles_Resize;
            this.lviewFiles.KeyDown += LviewFiles_KeyDown;
            this.tboxFilename.KeyDown += TboxFilename_KeyDown;
            this.tboxFilename.KeyPress += TboxFilename_KeyPress;
            this.btnFileAdd.Click += BtnFileAdd_Click;
            this.btnFileRemove.Click += BtnFileRemove_Click;
            this.btnFileClear.Click += BtnFileClear_Click;
            this.btnParsing.Click += BtnParsing_Click;
            this.btnEqpSelector.Click += BtnEqpSelector_Click;

            // Capture Image 
            this.pnlFilesButtons.DoubleClick += this.Capture_FullScreen;
            this.pnlEISInfo.DoubleClick += this.Capture_EISInformation;
            this.pnlEqInfo01.DoubleClick += this.Capture_EISInformation;
            this.pnlOptionButton.DoubleClick += this.Capture_LogArea;
            this.pnlOptionCheck.DoubleClick += this.Capture_LogArea;
            this.pnlOptions.DoubleClick += this.Capture_LogArea;
            this.tabLogViewer.DoubleClick += this.Capture_LogArea;
            this.pnlStatus.DoubleClick += this.LogFolderOpen;

            // Option
            this.chkShowGroupColumns.CheckedChanged += this.ChkShowGroupColumns_CheckedChanged;
            this.chkHideLinktest.CheckedChanged += Filter_CheckedChanged;
            this.chkHidTID.CheckedChanged += Filter_CheckedChanged;
            this.chkHideTraceData.CheckedChanged += Filter_CheckedChanged;

            this.btnClearFilter.Click += BtnClearFilter_Click;
            this.btnClearGroupBy.Click += this.BtnClearGroupBy_Click;
            this.btnColumnResize.Click += BtnColumnResize_Click;
            this.btnMongoDB.Click += this.BtnMongoDB_Click;
            this.btnMarkingFilter.Click += this.BtnMarkingFilter_Click;
            this.btnOpenLog.Click += BtnOpenLog_Click;
            this.btnSaveLog.Click += BtnSaveLog_Click;
            this.btnSecsDefine.Click += BtnSecsDefine_Click;
            this.btnOpenWorkFlow.Click += BtnOpenWorkFlow_Click;
            this.btnClearDownload.Click += BtnClearDownload_Click;
            this.btnMessageReplyTime.Click += this.BtnMessageReplyTime_Click;
            this.btnDeploySite.Click += this.BtnDeploySite_Click;
            this.btnTest01.Click += this.BtnTest01_Click;
            this.chkGridDTGroupKey.ItemCheckedChanged += this.ChkGridDTGroupKey_ItemCheckedChanged;

            // StatusBar
            this.tboxLineNumber.KeyDown += TboxLineNumber_KeyDown;
            this.tboxLineNumber.KeyPress += TboxLineNumber_KeyPress;
            this.cboxLineNumber.SelectedIndexChanged += CboxLineNumber_SelectedIndexChanged;
            this.btnBookmark.Click += BtnBookmark_Click;
            this.btnBookmarkClear.Click += BtnBookmarkClear_Click;

            // Grid
            this.grid.DataBindingComplete += RadGrid_DataBindingComplete;
            this.grid.SelectionChanged += RadGrid_SelectionChanged;
            this.grid.ViewCellFormatting += RadGrid_ViewCellFormatting;
            this.grid.CellDoubleClick += RadGrid_CellDoubleClick;
            this.grid.KeyDown += RadGrid_KeyDown;
            this.grid.KeyUp += RadGrid_KeyUp;
            this.grid.CellClick += RadGrid_CellClick;
        }

        private void FrmLogParser_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.ServerName)) return;
            if (string.IsNullOrEmpty(this.EquipmentID)) return;

            this.LogParser.ServerName = this.ServerName;
            this.LogParser.EquipmentID = this.EquipmentID;
            this.BtnEqpSelector_Click(this.btnEqpSelector, new EventArgs());
        }

        private void FrmLogParser_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.LogParser != null) this.LogParser.SaveGridHeader(this.grid);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    case Keys.F1:
                        Process.Start("IEXPLORE.EXE", "http://pms.e1soft.co.kr:8090/Deploy/eqview/");
                        break;
                    case Keys.F2:
                        this.Location = new Point(0, 0);
                        this.Size = new Size(800, 600);
                        break;
                    case Keys.F3:
                        if (this.FindDialog != null) this.FindDialog.Next();
                        break;
                    case Keys.F5:
                        this.BtnParsing_Click(this.btnParsing, new EventArgs());
                        break;
                    case Keys.F6:
                        this.grid.BestFitColumns(BestFitColumnMode.DisplayedCells);
                        break;
                    case Keys.PageDown:
                        if (this.grid.RowCount == this.grid.CurrentRow.Index + 1)
                        {
                            int index = this.grid.CurrentRow.Index;
                            this.BtnParsing_Click(this.btnParsing, new EventArgs());
                            this.grid.CurrentRow = this.grid.Rows[index];
                            return true;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        #endregion

        #region [ Control Event ] ---------------------------------------------

        private void Control_DragDrop(object sender, DragEventArgs e)
        {
            XLogger.Instance.Info(e);
            if (this.chkAutoClear.Checked) this.lviewFiles.Items.Clear();

            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            foreach (string filePath in files)
            {
                ListViewItem lviewItem = this.lviewFiles.Items.Add(Path.GetFileName(filePath));
                lviewItem.Checked = true;
                lviewItem.Tag = filePath;
            }

            this.tboxEISInfo01.Clear();
            this.tboxEISInfo02.Clear();
            this.tboxEISInfo03.Clear();
            this.tboxEISInfo04.Clear();
            this.tboxEISInfo05.Clear();
            this.tboxEISInfo07.Clear();
            this.tboxEISInfo06.Clear();
            this.tboxFilename.Clear();
            this.tboxLog.Clear();
            this.grid.DataSource = null;

            this.BtnParsing_Click(this.btnParsing, new EventArgs());
        }

        private void Control_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
        }

        private void TboxLog_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyData & Keys.Control) == Keys.Control && (e.KeyData & Keys.F) == Keys.F)
            {
                if (this.FindDialog == null)
                {
                    this.FindDialog = new FrmFindDialog(this.tboxLog);
                    this.FindDialog.StartPosition = FormStartPosition.Manual;
                    this.FindDialog.Location = this.grid.PointToScreen(new Point(10, 10));
                    this.FindDialog.FormClosed += (object sender1, FormClosedEventArgs e1) => { this.FindDialog = null; };
                    this.FindDialog.FInd += (object sender1, EventArgs e1) => { };
                    this.FindDialog.Show();
                }
                else
                {
                    this.FindDialog.Activate();
                }

                this.FindDialog.SelectedText = this.tboxLog.SelectedText;
            }
        }


        #region [ File List Events ]

        private void LviewFiles_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lviewFiles.Items.Count < 1) return;
                if (this.lviewFiles.SelectedItems.Count < 1) return;

                int index = -1;
                index = this.lviewFiles.SelectedItems[0].Index;
                LogFile logFile = this.lviewFiles.Items[index].Tag as LogFile;
                if (logFile == null) return;

                this.tboxFilename.Text = logFile.FileName;
                this.tboxFilename.Tag = logFile;
                if (string.IsNullOrEmpty(this.tboxFilename.Text) == false && this.tboxFilename.Text.Length > 6)
                {
                    this.tboxFilename.SelectionStart = this.tboxFilename.Text.Length - 6;
                    this.tboxFilename.SelectionLength = 2;
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void LviewFiles_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                System.Windows.Forms.SortOrder sorting = System.Windows.Forms.SortOrder.None;
                switch (this.lviewFiles.Sorting)
                {
                    case System.Windows.Forms.SortOrder.None:
                        sorting = System.Windows.Forms.SortOrder.Ascending;
                        break;
                    case System.Windows.Forms.SortOrder.Ascending:
                        sorting = System.Windows.Forms.SortOrder.Descending;
                        break;
                    case System.Windows.Forms.SortOrder.Descending:
                        sorting = System.Windows.Forms.SortOrder.None;
                        break;
                }

                this.lviewFiles.Sorting = sorting;
                this.lviewFiles.ListViewItemSorter = new ListViewItemComparer(e.Column, this.lviewFiles.Sorting);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void LviewFiles_Resize(object sender, EventArgs e)
        {
            int width = this.lviewFiles.Width - 32;
            if (this.lviewFiles.Columns.Count == 2)
            {
                this.lviewFiles.Columns[0].Width = width - 120;
                this.lviewFiles.Columns[1].Width = 120;
            }
            else
            {
                int widthColumn = width / this.lviewFiles.Columns.Count;
                foreach (ColumnHeader header in this.lviewFiles.Columns)
                    header.Width = widthColumn;
            }
        }

        private void LviewFiles_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    List<ListViewItem> items = new List<ListViewItem>();
                    foreach (ListViewItem item in this.lviewFiles.SelectedItems) items.Add(item);
                    foreach (ListViewItem item in items) this.lviewFiles.Items.Remove(item);
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void TboxFilename_KeyDown(object sender, KeyEventArgs e)
        {
        }

        private void TboxFilename_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                this.BtnFileAdd_Click(this.btnFileAdd, new EventArgs());
                if (string.IsNullOrEmpty(this.tboxFilename.Text) == false && this.tboxFilename.Text.Length > 6)
                {
                    this.tboxFilename.SelectionStart = this.tboxFilename.Text.Length - 6;
                    this.tboxFilename.SelectionLength = 2;
                    this.tboxFilename.Focus();
                }

                e.Handled = true;
            }
        }

        private void BtnFileAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = this.tboxFilename.Text;
                if (string.IsNullOrEmpty(fileName)) return;

                foreach (ListViewItem item in this.lviewFiles.Items)
                    if (string.Compare(item.Text, fileName, true) == 0) return;

                LogFile srcLogFile = this.tboxFilename.Tag as LogFile;
                if (srcLogFile == null)
                {
                    if (this.lviewFiles.Items.Count < 1) return;
                    srcLogFile = this.lviewFiles.Items[0].Tag as LogFile;
                    if (srcLogFile == null) return;
                }

                string fullName = Path.Combine(srcLogFile.DirectoryName, fileName);
                LogFile newLogFile = new LogFile(fullName) { Account = srcLogFile.Account };

                ListViewItem lviewItem = this.lviewFiles.Items.Add(newLogFile.FileName);
                lviewItem.Tag = newLogFile;
                lviewItem.Checked = true;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnFileRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.lviewFiles.SelectedItems.Count <= 0) return;

                this.lviewFiles.SelectedItems[0].Remove();
                this.tboxFilename.Text = string.Empty;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnFileClear_Click(object sender, EventArgs e)
        {
            this.Text = $"{this.WindowText} - Ver. {Application.ProductVersion}";

            this.lviewFiles.Items.Clear();
            this.tboxLog.Clear();
            this.tboxException.Clear();

            this.grid.DataSource = null;
        }

        private void BtnParsing_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                System.GC.Collect();
                this.DownLoad_Parsing();

                StandardData[] array = this.Filtering(this.StandardCollection.ToArray());
                this.grid.AutoBinding(array);
                if (this.FrmMessageReplyTime != null)
                {
                    this.FrmMessageReplyTime.StandardCollection.Clear();
                    this.FrmMessageReplyTime.StandardCollection.AddRange(array);
                    this.FrmMessageReplyTime.Generate();
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private StandardData[] Filtering(StandardData[] values)
        {
            StandardData[] array = null;
            try
            {
                array = values.ToArray();
                if (this.chkHideLinktest.Checked) array = array.Where(item => item.Column1?.ToUpper() != "LINKTEST").ToArray();
                if (this.chkHidTID.Checked) array = array.Where(item => item.Server?.ToUpper() != "TID" || (item.Server?.ToUpper() == "TID" && item.Level?.ToUpper() != "INFO")).ToArray();
                if (this.chkHideTraceData.Checked)
                {
                    array = array.Where(item => item.MessageName?.ToUpper() != "S6F0").ToArray();
                    array = array.Where(item => item.MessageName?.ToUpper() != "S6F1").ToArray();
                    array = array.Where(item => item.MessageName?.ToUpper() != "S6F2").ToArray();
                    array = array.Where(item => item.MessageName?.ToUpper() != "TRACEDATAREPORT").ToArray();
                }

                return array;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
                return values;
            }
        }

        private void BtnEqpSelector_Click(object sender, EventArgs e)
        {
            if (this.LogParser == null) return;

            List<LogFile> lstLogFile = new List<LogFile>();
            foreach (ListViewItem item in this.lviewFiles.Items)
            {
                if (item.Tag != null && item.Tag.GetType() == typeof(LogFile))
                    lstLogFile.Add((LogFile)item.Tag);
            }

            // LogPaser > FrmEqSelector
            LogFile[] logfiles = this.LogParser.FileSelector(this, lstLogFile.ToArray());
            if (logfiles == null || logfiles.Length < 1) return;

            if (this.chkAutoClear.Checked) this.BtnFileClear_Click(this.btnFileClear, new EventArgs());
            this.cboxLineNumber.Items.Clear();
            this.cboxLineNumber.Text = string.Empty;
            if (this.Equipment != null)
            {
                this.tboxEISInfo01.Text = this.Equipment.EquipmentID;
                this.tboxEISInfo02.Text = this.Equipment.DisplayName.Replace("EQP_NAME=", "").Split(new string[] { Environment.NewLine }, StringSplitOptions.None).FirstOrDefault();
                this.tboxEISInfo02.Text += $" / {this.Equipment.GemSettingID}";
                this.tboxEISInfo03.Text = $"{this.Equipment.ModelID} / {this.Equipment.Version}";
                this.tboxEISInfo04.Text = $"[{this.Equipment.Facility}]  {this.Equipment.Line}";
                this.tboxEISInfo05.Text = $"[{this.Equipment.ProcessSegmentID}]  {this.Equipment.ProcessSegmentName}";
                this.tboxEISInfo06.Text = $"{this.Equipment.ServerIP} / {this.Equipment.EquipmentIP}:{this.Equipment.Port}";
                this.tboxEISInfo07.Text = $"[MES] {this.Equipment.MesSubject} / {this.Equipment.MesService}";
                this.LogParser.ModelID = this.Equipment.ModelID;
            }

            foreach (LogFile logfile in logfiles)
            {
                this.tboxFilename.Tag = logfile;
                this.tboxFilename.Text = logfile.FileName;
                this.BtnFileAdd_Click(this.btnFileAdd, new EventArgs());
            }
            this.tboxFilename.Tag = null;

            if (this.chkAutoClear.Checked)
                this.BtnParsing_Click(this.btnParsing, new EventArgs());
        }

        #endregion

        #region [ Screen Capture & Log Folder Open ]

        /// <summary>
        /// Capture of EIS Information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_EISInformation(object sender, EventArgs e)
        {
            Bitmap bitmap = this.pnlEISInfo.ControlCapture();
        }

        /// <summary>
        /// Capture of Full Screen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_FullScreen(object sender, EventArgs e)
        {
            Bitmap bitmap = this.ControlCapture();
        }

        /// <summary>
        /// Capture of Grid Area
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_Grid(object sender, EventArgs e)
        {
            Bitmap bitmap = this.grid.ControlCapture();
        }

        /// <summary>
        /// Capture of Log Area
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Capture_LogArea(object sender, EventArgs e)
        {
            Bitmap bitmap = this.pnlLogView.ControlCapture();
        }

        /// <summary>
        /// 로그폴더 열기 or Capture_FullScreen
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void LogFolderOpen(object sender, EventArgs e)
        {
            if (this.lviewFiles.Items.Count < 1)
            {
                this.IsLogFolderOpen = true;
                this.pnlStatus.BackColor = Color.FromArgb(20, 255, 0, 0);
                return;
            }

            if (this.IsLogFolderOpen)
            {
                /* 지정된 PC에서...
                var macAddress =
                    (
                    from nic in NetworkInterface.GetAllNetworkInterfaces()
                    where nic.OperationalStatus == OperationalStatus.Up
                    select nic.GetPhysicalAddress().ToString()
                    ).FirstOrDefault();
                string[] permissions = new string[] { "00FF746EA3CB" };
                if (!permissions.Contains(macAddress)) return;
                */
                string filePath = this.lviewFiles.Items[0].Tag as string;
                string path = System.IO.Path.GetDirectoryName(filePath);
                Process.Start(path);
            }
        }

        #endregion

        #region [ Option Events ]

        private void ChkShowGroupColumns_CheckedChanged(object sender, EventArgs e)
        {
            this.grid.ShowGroupedColumns = this.chkShowGroupColumns.Checked;
        }

        private void Filter_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                StandardData[] array = this.Filtering(this.StandardCollection.ToArray());
                this.grid.AutoBinding(array);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnClearFilter_Click(object sender, EventArgs e)
        {
            this.grid.MasterTemplate.FilterDescriptors.Clear();
        }

        private void BtnClearGroupBy_Click(object sender, EventArgs e)
        {
            this.grid.MasterTemplate.GroupDescriptors.Clear();
        }

        private void BtnColumnResize_Click(object sender, EventArgs e)
        {
            this.grid.BestFitColumns(BestFitColumnMode.DisplayedCells);
        }

        private void BtnMongoDB_Click(object sender, EventArgs e)
        {
            string equipmentID = this.Equipment?.EquipmentID;
            string start = string.Empty;
            string end = string.Empty;
            if (this.StandardCollection != null && this.StandardCollection.Count > 0)
            {
                start = this.StandardCollection.First()?.DateTime.ToString("yyyy-MM-ddTHH:mm:ss");
                end = this.StandardCollection.Last()?.DateTime.ToString("yyyy-MM-ddTHH:mm:ss");
            }

#if DEBUG
            FrmFDCMongo frmFDCMongo = new FrmFDCMongo();
            frmFDCMongo.EquipmentID = equipmentID;
            frmFDCMongo.DateTimeStart = this.StandardCollection.Last().DateTime;
            frmFDCMongo.DateTimeEnd = this.StandardCollection.Last().DateTime;
            frmFDCMongo.Show();
#else
            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = Application.ExecutablePath;
            processStartInfo.WorkingDirectory = Environment.CurrentDirectory;
            processStartInfo.Arguments = $"FrmFDCMongo {equipmentID} {start} {end}";
            Process process = Process.Start(processStartInfo);
#endif
        }

        private void BtnMarkingFilter_Click(object sender, EventArgs e)
        {
            XLogger.Instance.Info();
            List<string> lstCondition = new List<string>();
            foreach (GridViewColumn column in this.grid.Columns)
            {
                foreach (BaseFormattingObject formatting in column.ConditionalFormattingObjectList)
                {
                    ExpressionFormattingObject express = formatting as ExpressionFormattingObject;
                    if (express == null) continue;
                    if (string.Compare(express.Name, "Marking", true) != 0) continue;

                    lstCondition.Add(express.Expression);
                    XLogger.Instance.Debug($"[{column.Name}] {express.Expression}");
                }
            }

            StandardCollection template = new StandardCollection();
            bool flag = true;
            foreach (StandardData data in this.grid.DataBindingItems)
            {
                flag = false;
                foreach (string conditon in lstCondition)
                {
                    flag = this.CheckShowCondition(data, conditon);
                    if (flag == true) break;
                }
                if (flag) template.Add(data);
            }
            this.grid.AutoBinding(template.ToArray());
        }

        private bool CheckShowCondition(StandardData data, string conditon)
        {
            try
            {
                bool flag = true;
                string[] operands = conditon.Split(new string[] { "AND" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string operand in operands)
                {
                    string[] values = operand.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                    if (values.Length != 2) continue;

                    string propertyName = values[0].Trim();
                    string valueB = values[1].Trim().Replace("'", "");
                    string valueA = data.PropertyGet(propertyName);
                    if (valueA != valueB) flag = false;
                }

                return flag;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
                return false;
            }
        }

        private void BtnOpenLog_Click(object sender, EventArgs e)
        {
            try
            {
                List<string> lstFullName = new List<string>();
                foreach (ListViewItem lviewItem in this.lviewFiles.Items)
                {
                    if (lviewItem.Checked == false) continue;
                    XLogger.Instance.Info(lviewItem.Text);

                    LogFile logFile = lviewItem.Tag as LogFile;
                    if (logFile == null) continue;

                    lstFullName.Add(logFile.DestFullName);
                }

                foreach (string fullName in lstFullName)
                    Process.Start(fullName);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnSaveLog_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog();
                if (dialog.ShowDialog() != DialogResult.OK) return;

                string pathCopyTo = $"{dialog.SelectedPath}{Path.DirectorySeparatorChar}{this.Equipment.EquipmentID}{Path.DirectorySeparatorChar}";
                if (System.IO.Directory.Exists(pathCopyTo) == false) System.IO.Directory.CreateDirectory(pathCopyTo);

                List<string> lstFilePath = new List<string>();
                foreach (ListViewItem lviewItem in this.lviewFiles.Items)
                {
                    if (lviewItem.Checked == false) continue;
                    XLogger.Instance.Info(lviewItem.Text);

                    string sourceFileName = lviewItem.Tag as string;
                    string fileName = System.IO.Path.GetFileName(sourceFileName);
                    string destPath = GlobalVariable.Instance.DownloadPath;
                    if (System.IO.Directory.Exists(destPath) == false) System.IO.Directory.CreateDirectory(destPath);

                    string destFileName = $@"{destPath}{fileName}";
                    if (this.chkDownload.Checked == false) System.IO.File.Copy(sourceFileName, destFileName, true);
                    sourceFileName = destFileName;
                    string copyTo = $"{pathCopyTo}{fileName}";

                    System.IO.File.Copy(sourceFileName, copyTo, true);
                    lstFilePath.Add(copyTo);
                }

                if (lstFilePath.Count == 0) return;
                Process.Start("explorer.exe", $"/select,\"{lstFilePath[0]}\"");
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnSecsDefine_Click(object sender, EventArgs e)
        {
            if (this.LogParser == null || this.LogParser.SECSDefine == null) return;

            FrmSecsDefine frm = new FrmSecsDefine(this.LogParser.SECSDefine);
            frm.StartPosition = FormStartPosition.Manual;
            int x = this.Location.X + this.Width - frm.Width - 32;
            int y = this.Location.Y + 32;
            frm.Location = new Point(x, y);
            frm.Text = $"{this.Equipment.ModelID} - {this.Equipment.GemSettingID}"; // this.tboxEqModelID.Text;
            frm.Show(this);
        }

        private void BtnOpenWorkFlow_Click(object sender, EventArgs e)
        {
            try
            {
                FrmWorkFlow dlg = new FrmWorkFlow();
                dlg.Owner = this;
                dlg.Size = this.Size;
                dlg.Location = this.Location;
                dlg.StartPosition = FormStartPosition.Manual;
                dlg.Text = $"{this.Equipment.ModelID} - {this.Equipment.RunningVersion}";
                dlg.Equipment = this.Equipment;
                dlg.Show();
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void BtnClearDownload_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dlgResult = MessageBox.Show($"로컬에 다운로드 된 로그 파일들을 삭제하시겠습니까?", "로그삭제", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                if (dlgResult != DialogResult.OK) return;

                this.Cursor = Cursors.WaitCursor;

                string path = string.Empty;
                path = GlobalVariable.Instance.DownloadPath;
                if (System.IO.Directory.Exists(path)) System.IO.Directory.Delete(path, true);
                path = GlobalVariable.Instance.WorkflowPath;
                if (System.IO.Directory.Exists(path)) System.IO.Directory.Delete(path, true);
                path = GlobalVariable.Instance.DefaultPath + "Logs" + Path.DirectorySeparatorChar;
                if (System.IO.Directory.Exists(path)) System.IO.Directory.Delete(path, true);

                MessageBox.Show($"다운로드 및 로그 파일들이 삭제 되었습니다.", "삭제", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void BtnMessageReplyTime_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.StandardCollection == null || this.StandardCollection.Count < 1) return;

                FrmMessageReplyTime1 frm = new FrmMessageReplyTime1(this.StandardCollection);
                this.FrmMessageReplyTime = frm;
                frm.GridView = this.grid;
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.FormClosed += new FormClosedEventHandler(delegate (object ddd, FormClosedEventArgs arg) { this.FrmMessageReplyTime = null; });
                frm.Show(this);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex, true);
            }
        }

        private void BtnDeploySite_Click(object sender, EventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://pms.e1soft.co.kr:8090/Deploy/eqview/");
        }

        private void BtnTest01_Click(object sender, EventArgs e)
        {
        }

        private void ChkGridDTGroupKey_ItemCheckedChanged(object sender, RadCheckedListDataItemEventArgs e)
        {
            GridViewEx.eDateTimeGroupKey groupKey = GridViewEx.eDateTimeGroupKey.None;
            foreach (RadListDataItem item in this.chkGridDTGroupKey.CheckedItems)
            {
                GridViewEx.eDateTimeGroupKey itemKey = (GridViewEx.eDateTimeGroupKey)item.Value;
                groupKey |= itemKey;
            }

            this.grid.DateTimeGroupKey = groupKey;
        }

        #endregion

        #region [ StatusBar Events ]

        private void TboxLineNumber_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.KeyData == Keys.Enter)
            //    this.BtnGoLineNumber_Click(this.btnGoLineNumber, new EventArgs());
        }

        private void TboxLineNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                this.BtnBookmark_Click(this.btnBookmark, new EventArgs());
                e.Handled = true;
            }
        }

        private void CboxLineNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            KeyValuePair<string, string> cboxItem = (KeyValuePair<string, string>)this.cboxLineNumber.SelectedItem;

            string lineNumber = cboxItem.Value;
            this.tboxLineNumber.Text = lineNumber;
            this.BtnBookmark_Click(null, null);
        }

        private void BtnBookmark_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                int lineNumber = -1;
                int.TryParse(this.tboxLineNumber.Text, out lineNumber);
                foreach (GridViewRowInfo row in this.grid.Rows)
                {
                    try
                    {
                        StandardData standardData = row.DataBoundItem as StandardData;
                        if (standardData == null) continue;
                        if (lineNumber <= standardData.LineNumber)
                        {
                            this.grid.Focus();
                            row.IsSelected = false;
                            row.IsCurrent = false;
                            row.IsSelected = true;
                            row.IsCurrent = true;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        XLogger.Instance.Debug(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void BtnBookmarkClear_Click(object sender, EventArgs e)
        {
            this.cboxLineNumber.Items.Clear();
        }

        #endregion

        #endregion

        #region [ Grid ] ------------------------------------------------------

        private void RadGrid_Setting()
        {
            this.grid.MultiSelect = true;
            this.grid.Columns.Clear();
            this.grid.TableElement.RowHeight = 20;
            this.grid.InsertContextMenu(4, "Copy Message", RadGrid_CopyMessage);
            this.grid.DateTimeGroupKey = GridViewEx.eDateTimeGroupKey.Date;

            if (this.LogParser != null) this.LogParser.SetGridHeader(this.grid);
        }

        private void RadGrid_KeyUp(object sender, KeyEventArgs e)
        {
            this.RadGridControlKey = e.Control;
            if (e.KeyData == Keys.Escape) this.RadGrid_RemoveFormatting(sender, new string[] { "Marking" });
        }

        private void RadGrid_RemoveFormatting(object sender, params string[] names)
        {
            try
            {
                Dictionary<GridViewColumn, List<BaseFormattingObject>> dicRemove = new Dictionary<GridViewColumn, List<BaseFormattingObject>>();
                RadGridView rgrid = sender as RadGridView;
                foreach (GridViewDataColumn column in rgrid.Columns)
                {
                    foreach (BaseFormattingObject format in column.ConditionalFormattingObjectList)
                    {
                        if (names.Contains(format.Name))
                        {
                            if (dicRemove.ContainsKey(column) == false)
                                dicRemove.Add(column, new List<BaseFormattingObject>());
                            dicRemove[column].Add(format);
                        }
                    }
                }

                foreach (GridViewColumn column in dicRemove.Keys)
                {
                    foreach (BaseFormattingObject format in dicRemove[column])
                        column.ConditionalFormattingObjectList.Remove(format);
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void RadGrid_KeyDown(object sender, KeyEventArgs e)
        {
            this.RadGridControlKey = e.Control;
        }

        private void RadGrid_CellClick(object sender, GridViewCellEventArgs e)
        {
            try
            {
                RadGridView rgrid = sender as RadGridView;
                if (rgrid == null) rgrid = this.grid;
                if (this.RadGridControlKey == false) return;

                foreach (GridViewDataColumn column in rgrid.Columns)
                {
                    foreach (BaseFormattingObject obj in column.ConditionalFormattingObjectList)
                    {
                        if (new string[] { "Marking" }.Contains(obj.Name))
                        {
                            ExpressionFormattingObject formatting = obj as ExpressionFormattingObject;
                            formatting.Expression += $" AND {e.Column.Name} = '{e.Value}'";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void RadGrid_CellDoubleClick(object sender, GridViewCellEventArgs e)
        {
            try
            {
                RadGridView rgrid = sender as RadGridView;
                if (rgrid == null) rgrid = this.grid;

                StandardData standardData = e.Row.DataBoundItem as StandardData;
                if (standardData != null)
                {
                    this.tboxLineNumber.Text = standardData.LineNumber.ToString();
                    this.tboxLineNumber.Tag = e.Row;

                    string itemKey = $"[{standardData.DateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")}] Line:{standardData.LineNumber.ToString().PadRight(10)} {standardData.MessageName} / {standardData.Value}";
                    string itemValue = standardData.LineNumber.ToString();
                    KeyValuePair<string, string> cboxItem = new KeyValuePair<string, string>(itemKey, itemValue);
                    if (!this.cboxLineNumber.Items.Contains(cboxItem)) this.cboxLineNumber.Items.Add(cboxItem);
                    this.cboxLineNumber.SelectedItem = cboxItem;
                }
                if (e.Value == null) return;

                var value = e.Value;
                if (e.Value.GetType() == typeof(DateTime))
                {
                    var tempData = (DateTime)e.Value;
                    value = tempData.ToString("yyyy-MM-dd HH:mm:ss.fff");
                }

                ExpressionFormattingObject formatting = new ExpressionFormattingObject($"Marking", $"{e.Column.Name} = '{value}'", true);
                formatting.RowBackColor = Color.FromArgb(128, 0, 255, 0);
                rgrid.Columns[e.Column.Name].ConditionalFormattingObjectList.Add(formatting);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void RadGrid_ViewCellFormatting(object sender, CellFormattingEventArgs e)
        {
            if (e.CellElement is GridRowHeaderCellElement && e.Row is GridViewDataRowInfo)
            {
#if ROW_INDEX
                GridDataView dataView = this.grid.MasterTemplate.DataView as GridDataView;
                e.CellElement.Text = (dataView.Indexer.Items.IndexOf(e.Row) + 1).ToString();
#else
                StandardData standardData = e.Row.DataBoundItem as StandardData;
                e.CellElement.Text = (standardData != null ? standardData.LineNumber.ToString() : "");
#endif
            }
            else
            {
                e.CellElement.ResetValue(LightVisualElement.TextImageRelationProperty, Telerik.WinControls.ValueResetFlags.Local);
            }
        }

        private void RadGrid_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e)
        {
            RadGridView rgrid = sender as RadGridView;
            if (rgrid == null) return;

            if (rgrid.Columns.Contains("LineNumber")) rgrid.Columns["LineNumber"].IsVisible = false;
            if (rgrid.Columns.Contains("DateTime")) rgrid.Columns["DateTime"].FormatString = "{0:yyyy-MM-dd HH:mm:ss.fff}";
            if (rgrid.Columns.Contains("Service")) rgrid.Columns["Service"].IsVisible = false;
            if (rgrid.Columns.Contains("Body")) rgrid.Columns["Body"].IsVisible = false;

            if (rgrid.Columns.Contains("Level"))
            {
                this.RadGrid_RemoveFormatting(rgrid, "Level_Error");
                rgrid.Columns["Level"].TextAlignment = ContentAlignment.MiddleCenter;
                ExpressionFormattingObject formatting = new ExpressionFormattingObject("Level_Error", "Level='ERROR'", true);
                formatting.RowBackColor = Color.FromArgb(128, 255, 0, 0);
                rgrid.Columns["Level"].ConditionalFormattingObjectList.Add(formatting);
            }

            if (rgrid.Columns.Contains("Type"))
            {
                this.RadGrid_RemoveFormatting(rgrid, "Type_Error");
                ExpressionFormattingObject formatting = new ExpressionFormattingObject($"Type_Error", "Server<>'TID' and Type='ERROR'", true);
                formatting.RowBackColor = Color.FromArgb(128, 255, 0, 0);
                rgrid.Columns["Type"].ConditionalFormattingObjectList.Add(formatting);
            }

            if (rgrid.Columns.Contains("Return"))
            {
                this.RadGrid_RemoveFormatting(rgrid, "Return_Error");
                rgrid.Columns["Return"].TextAlignment = ContentAlignment.MiddleCenter;
                ExpressionFormattingObject formatting = new ExpressionFormattingObject($"Return_Error", "Return<>'0'", true);
                formatting.RowBackColor = Color.FromArgb(128, 255, 0, 0);
                rgrid.Columns["Return"].ConditionalFormattingObjectList.Add(formatting);
            }

            rgrid.BestFitColumns(BestFitColumnMode.DisplayedCells);
        }

        private void RadGrid_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.chkLogSynchronization.Checked == false) return;

                this.Cursor = Cursors.WaitCursor;
                RadGridView rgrid = sender as RadGridView;
                if (rgrid == null) return;
                if (rgrid.SelectedRows.Count < 1) return;

                StandardData data = rgrid.SelectedRows.FirstOrDefault().DataBoundItem as StandardData;
                if (data == null) return;

                int dataLineNumber = data.LineNumber - 1;
                int startLineNumber = dataLineNumber - 10;
                int bottomLineNumber = dataLineNumber + 100;
                int dataIndex = this.tboxLog.Text.IndexOf($"{data.LineNumber.ToString("000000")}:");
                int difference = dataIndex - this.tboxLog.GetFirstCharIndexFromLine(dataLineNumber);

                this.tboxLog.SuspendLayout();
                if (bottomLineNumber >= this.tboxLog.Lines.Length) bottomLineNumber = this.tboxLog.Lines.Length - 1;
                this.tboxLog.SelectionStart = this.tboxLog.GetFirstCharIndexFromLine(bottomLineNumber) + difference;
                this.tboxLog.ScrollToCaret();

                if (startLineNumber < 0) startLineNumber = 0;
                this.tboxLog.SelectionStart = this.tboxLog.GetFirstCharIndexFromLine(startLineNumber) + difference;
                this.tboxLog.ScrollToCaret();

                this.tboxLog.SelectionStart = this.tboxLog.GetFirstCharIndexFromLine(dataLineNumber) + difference;
                this.tboxLog.SelectionLength = 6;
                this.tboxLog.ScrollToCaret();
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
            finally
            {
                this.tboxLog.ResumeLayout();
                this.Cursor = Cursors.Default;
            }
        }

        private void RadGrid_CopyMessage(object sender, params object[] args)
        {
            try
            {
                if (this.grid.SelectedRows.Count < 1) return;

                StandardData data = this.grid.SelectedRows[0].DataBoundItem as StandardData;
                string strBody = string.Empty;
                if (data != null && data.Body != null) strBody = data.Body.ToString();
                Clipboard.SetText($"{strBody}");
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        #endregion

        #region [ Method ] ----------------------------------------------------

        /// <summary>
        /// [CheckPoint] 로그파일을 로컬에 복제(다운로드)후, 데이터를 생성한다
        /// </summary>
        /// <returns></returns>
        private StandardCollection DownLoad_Parsing()
        {
            try
            {
                this.tboxLog.Clear();
                this.tboxException.Clear();
                this.StandardCollection.Clear();

                List<string> lstFileName = new List<string>();
                string strTitle = string.Empty;
                string destPath = string.Empty;

                // Process Unit: File
                foreach (ListViewItem lviewItem in this.lviewFiles.Items)  //jhlim 20250202
                {
                    if (lviewItem.Checked == false) continue;
                    XLogger.Instance.Info(lviewItem.Text);

                    LogFile logFile = lviewItem.Tag as LogFile;
                    switch(logFile.Account.Access)
                    {
                        case AccessType.SMB:
                            {
                                FileInfo fileInfo = new FileInfo(logFile.FullName);
                                if (fileInfo.Exists == false) continue;

                                logFile.Length = fileInfo.Length;
                                if (lviewItem.SubItems.Count < 2) lviewItem.SubItems.Add(logFile.GetFileSize());
                                else lviewItem.SubItems[1].Text = logFile.GetFileSize();

                                if (this.chkDownload.Checked)
                                {
                                    destPath = Path.Combine(GlobalVariable.Instance.DownloadPath, this.Equipment.EquipmentID);
                                    if (Directory.Exists(destPath) == false) Directory.CreateDirectory(destPath);

                                    if (string.IsNullOrEmpty(strTitle)) strTitle = this.Equipment.MesName;
                                    logFile.DestFullName = Path.Combine(destPath, logFile.FileName);

                                    File.Copy(logFile.FullName, logFile.DestFullName, true);
                                }
                            }
                            break;
                        case AccessType.FTPS:
                            {
                                if (FtpsClient._host != logFile.Account.IPAddress)
                                    FtpsClient.Initialize(logFile.Account.IPAddress, logFile.Account.UserID, logFile.Account.Password);
                                FtpListItem ftpsFileInfo = FtpsClient.GetFileInfo(logFile.FullName);
                                if (ftpsFileInfo == null) continue;

                                logFile.Length = ftpsFileInfo.Size;
                                if (lviewItem.SubItems.Count < 2) lviewItem.SubItems.Add(logFile.GetFileSize());
                                else lviewItem.SubItems[1].Text = logFile.GetFileSize();

                                if (this.chkDownload.Checked)
                                {
                                    destPath = Path.Combine(GlobalVariable.Instance.DownloadPath, this.Equipment.EquipmentID);
                                    if (Directory.Exists(destPath) == false) Directory.CreateDirectory(destPath);

                                    if (string.IsNullOrEmpty(strTitle)) strTitle = this.Equipment.MesName;
                                    logFile.DestFullName = Path.Combine(destPath, logFile.FileName);

                                    FtpsClient.DownloadFtpsFile(logFile.FullName, logFile.DestFullName);
                                }
                            }
                            break;
                        case AccessType.SFTP:
                            break;
                        case AccessType.FTP:
                            break;
                    }

                    lstFileName.Add(logFile.DestFullName);
                }

                if (!string.IsNullOrEmpty(this.tboxEISInfo04.Text)) this.LogParser.ModelID = this.tboxEISInfo04.Text;
                if (this.SECSDefine != null) this.LogParser.SECSDefine = this.SECSDefine;
                this.LogParser.Parsing(lstFileName.ToArray());
                this.Text = $"{strTitle} - Ver. {Application.ProductVersion}";
                this.tboxLog.Text = this.LogParser.LogString.ToString();
                this.StandardCollection.AddRange(this.LogParser.StandardCollection);

                return this.StandardCollection;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
                return this.StandardCollection;
            }
        }

        /// <summary>
        /// [CheckPoint] 로그파일을 로컬에 복제후, 데이터를 생성한다
        /// </summary>
        /// <returns></returns>
        private StandardCollection xParsing()
        {
            try
            {
                this.tboxLog.Clear();
                this.tboxException.Clear();
                this.StandardCollection.Clear();

                List<string> lstFileName = new List<string>();
                string strTitle = string.Empty;

                // Process Unit: File
                foreach (ListViewItem lviewItem in this.lviewFiles.Items)  //jhlim 20250202
                {
                    if (lviewItem.Checked == false) continue;
                    XLogger.Instance.Info(lviewItem.Text);
                    
                    string fullPath = lviewItem.Tag as string;

                    //var sftpFileInfo = SftpClientWrapper.GetFileInfo(fullPath); 
                    var ftpsFileInfo = FtpsClient.GetFileInfo(fullPath);
                    //if (sftpFileInfo != null)
                    if (ftpsFileInfo != null)
                    {

                        //if (lviewItem.SubItems.Count < 2) lviewItem.SubItems.Add($"{((float)sftpFileInfo.Size / 1024 / 1024).ToString("F2")} MB");
                        //else lviewItem.SubItems[1].Text = $"{((float)sftpFileInfo.Size / 1024 / 1024).ToString("F2")} MB";
                        if (lviewItem.SubItems.Count < 2) lviewItem.SubItems.Add($"{((float)ftpsFileInfo.Size / 1024 / 1024).ToString("F2")} MB");
                        else lviewItem.SubItems[1].Text = $"{((float)ftpsFileInfo.Size / 1024 / 1024).ToString("F2")} MB";

                        if (this.chkDownload.Checked)
                        {
                            string destPath = GlobalVariable.Instance.DownloadPath;
                            if (System.IO.Directory.Exists(destPath) == false) System.IO.Directory.CreateDirectory(destPath);

                            if (string.IsNullOrEmpty(strTitle)) strTitle = System.IO.Path.GetFileNameWithoutExtension(fullPath);
                            string destFileName = $@"{destPath}{System.IO.Path.GetFileName(fullPath)}";
                            //SftpClientWrapper.DownloadSftpFile(fullPath, destFileName);
                            FtpsClient.DownloadFtpsFile(fullPath, destFileName);
                            fullPath = destFileName;
                        }
                    }
                    else
                    {
                        FileInfo fileInfo = new FileInfo(fullPath);   // 
                        if (fileInfo.Exists == false) continue;

                        if (lviewItem.SubItems.Count < 2) lviewItem.SubItems.Add($"{((float)fileInfo.Length / 1024 / 1024).ToString("F2")} MB");
                        else lviewItem.SubItems[1].Text = $"{((float)fileInfo.Length / 1024 / 1024).ToString("F2")} MB";

                        if (this.chkDownload.Checked)
                        {
                            string destPath = GlobalVariable.Instance.DownloadPath;
                            if (System.IO.Directory.Exists(destPath) == false) System.IO.Directory.CreateDirectory(destPath);

                            if (string.IsNullOrEmpty(strTitle)) strTitle = System.IO.Path.GetFileNameWithoutExtension(fullPath);
                            string destFileName = $@"{destPath}{System.IO.Path.GetFileName(fullPath)}";

                            if (fullPath != destFileName)
                            {
                                System.IO.File.Copy(fullPath, destFileName, true);
                            }
                            fullPath = destFileName;
                        }
                    }
                    lstFileName.Add(fullPath);
                }   // Process Unit: File

                if (!string.IsNullOrEmpty(this.tboxEISInfo04.Text)) this.LogParser.ModelID = this.tboxEISInfo04.Text;
                if (this.SECSDefine != null) this.LogParser.SECSDefine = this.SECSDefine;
                this.LogParser.Parsing(lstFileName.ToArray());
                this.Text = $"{strTitle} - Ver. {Application.ProductVersion}";
                this.tboxLog.Text = this.LogParser.LogString.ToString();
                this.StandardCollection.AddRange(this.LogParser.StandardCollection);

                return this.StandardCollection;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
                return this.StandardCollection;
            }
        }

        #endregion

    }

}
