using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DDUtilityApp.LOGPARSER.DATA;
using DDUtilityApp.LOGPARSER.PARSER;
using DDUtilityApp.SECS;
using JWH;
using JWH.CONTROL;
using Telerik.WinControls.UI;

namespace DDUtilityApp.LOGPARSER
{

    public partial class FrmLogParser03 : Form
    {

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

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

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

        private LogParser Parser { get; set; } = new EisParser();

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

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

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

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

        #endregion

        #region [ FrmLogParser03 ] --------------------------------------------

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

            this.rbtnParser0.Checked = true;
            XLogger.Instance.Control = this.tboxException;
        }

        private void SetLayout()
        {
            this.AllowDrop = true;
            this.Text = $"{this.WindowText} - Ver. {Application.ProductVersion}";

            this.tboxLog.AllowDrop = true;
            this.tboxLog.WordWrap = false;
            this.tboxLog.Multiline = true;
            this.tboxLog.HideSelection = false;
            this.tboxLog.ScrollBars = ScrollBars.Both;
            this.tboxLog.Font = new Font("돋움체", 9);
            this.tboxLog.SetTabWidth(4);

            this.tboxException.WordWrap = false;
            this.tboxException.Font = new Font("돋움체", 9);
            this.tboxException.SetTabWidth(4);

            this.lviewFiles.View = View.Details;
            ColumnHeader header = this.lviewFiles.Columns.Add("File Name");
            this.lviewFiles.CheckBoxes = true;
            this.lviewFiles.MultiSelect = false;
            this.lviewFiles.Sorting = System.Windows.Forms.SortOrder.Ascending;
            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;
#if !DEBUG
            this.btnTest01.Visible = false;
#endif

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

            this.cboxLineNumber.Font = new Font("돋움체", 9);
            this.cboxLineNumber.DisplayMember = "Key";
            this.cboxLineNumber.ValueMember = "Value";
        }

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

            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;

            // Option
            this.chkShowGroupColumns.CheckedChanged += this.ChkShowGroupColumns_CheckedChanged;
            this.chkHideLinktest.CheckedChanged += Filter_CheckedChanged;
            this.chkHidTID.CheckedChanged += Filter_CheckedChanged;
            this.chkHideTraceData.CheckedChanged += Filter_CheckedChanged;
            this.rbtnParser.CheckedChanged += RbtnParser_CheckedChanged;
            this.rbtnParser0.CheckedChanged += RbtnParser0_CheckedChanged;

            this.btnClearFilter.Click += BtnClearFilter_Click;
            this.btnColumnResize.Click += BtnColumnResize_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.btnTest01.Click += this.BtnTest01_Click;

            // StatusBar
            this.btnGoLineNumber.Click += BtnGoLineNumber_Click;
            this.tboxLineNumber.KeyDown += TboxLineNumber_KeyDown;
            this.tboxLineNumber.KeyPress += TboxLineNumber_KeyPress;
            this.cboxLineNumber.SelectedIndexChanged += CboxLineNumber_SelectedIndexChanged;

            // 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;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            try
            {
                switch (keyData)
                {
                    case Keys.F1:
                        //Process.Start($@"{Application.StartupPath}\DDEESUtility.pptx");
                        Process.Start($"http://jungwoois.dothome.co.kr");
                        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;
                }
            }
            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.tboxEqDescription.Clear();
            this.tboxEqModelID.Clear();
            this.tboxEquipmentID.Clear();
            this.tboxEqVersion.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;

                this.tboxFilename.Text = this.lviewFiles.Items[index].Tag as string;
                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;
            int headerWidth = width / this.lviewFiles.Columns.Count;
            foreach (ColumnHeader header in this.lviewFiles.Columns)
                header.Width = headerWidth;
        }

        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 = Path.GetFileName(this.tboxFilename.Text);
                if (string.IsNullOrEmpty(fileName)) return;
                foreach (ListViewItem item in this.lviewFiles.Items)
                    if (string.Compare(item.Text, fileName, true) == 0) return;

                ListViewItem lviewItem = this.lviewFiles.Items.Add(fileName);
                lviewItem.Tag = this.tboxFilename.Text;
                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.Parsing();

                StandardData[] array = this.Filtering(this.Collection.ToArray());
                this.grid.AutoBinding(array);
            }
            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)
        {
            try
            {
                FrmEqSelector dlg = new FrmEqSelector();
                dlg.Owner = this;
                dlg.Size = this.Size;
                dlg.StartPosition = FormStartPosition.CenterParent;
                dlg.Equipment = this.Equipment;
                dlg.SelectedLogFiles = this.LviewFiles_GetLogFile();
                DialogResult dlgResult = dlg.ShowDialog();
                if (dlgResult != DialogResult.OK) return;

                EisEquipment equipment = dlg.Equipment as EisEquipment;
                if (equipment == null) return;
                this.cboxLineNumber.Items.Clear();
                this.cboxLineNumber.Text = string.Empty;

                this.Equipment = equipment;
                this.SECSDefine = dlg.SECSDefine;

                if (this.chkAutoClear.Checked)
                    this.BtnFileClear_Click(this.btnFileClear, new EventArgs());

                foreach (LogFile logFile in dlg.SelectedLogFiles)
                {
                    this.tboxFilename.Text = logFile.FullName;
                    this.BtnFileAdd_Click(this.btnFileAdd, new EventArgs());
                }

                this.tboxEquipmentID.Text = equipment.EquipmentID;
                this.tboxEqModelID.Text = equipment.ModelID;
                this.tboxEqDescription.Text = equipment.DisplayName;
                this.tboxEqDescription2.Text = $"{equipment.ProcessSegmentID} {equipment.MesName}";
                this.tboxEqVersion.Text = equipment.Version;
                this.Parser.ModelID = equipment.ModelID;

                if (this.chkAutoClear.Checked)
                    this.BtnParsing_Click(this.btnParsing, new EventArgs());
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex, true);
            }
        }

        #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.Collection.ToArray());
                this.grid.AutoBinding(array);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void RbtnParser_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnParser.Checked)
            {
                this.Parser = new EisParser();
                this.BtnParsing_Click(this.btnParsing, null);
            }
        }

        private void RbtnParser0_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rbtnParser0.Checked)
            {
                this.Parser = new EisParser0();
                this.BtnParsing_Click(this.btnParsing, null);
            }
        }

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

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

        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> lstFileName = 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 destPath = GlobalVariable.Instance.DownloadPath;
                    if (System.IO.Directory.Exists(destPath) == false) System.IO.Directory.CreateDirectory(destPath);

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

                    lstFileName.Add(sourceFileName);
                }

                foreach (string filename in lstFileName)
                    Process.Start(filename);
            }
            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)
        {
            FrmSecsDefine frm = new FrmSecsDefine(this.Parser.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
            {
                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 BtnTest01_Click(object sender, EventArgs e)
        {
        }

        #endregion

        #region [ StatusBar Events ]

        private void BtnGoLineNumber_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 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.BtnGoLineNumber_Click(this.btnGoLineNumber, 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.BtnGoLineNumber_Click(null, null);
        }

        #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.AddColumn("LineNumber");
            this.grid.AddColumn("DateTime");
            this.grid.AddColumn("Level");
            this.grid.AddColumn("Server");
            this.grid.AddColumn("Service");
            this.grid.AddColumn("Type");
            this.grid.AddColumn("MessageName");
            this.grid.AddColumn("Return");
            this.grid.AddColumn("Value");
            this.grid.AddColumn("LotID");
            this.grid.AddColumn("CarrierID");
            this.grid.AddColumn("EquipmentID");
            this.grid.AddColumn("PortID");
            this.grid.AddColumn("HostPanelID");
            this.grid.AddColumn("PanelID");
            this.grid.AddColumn("PanelQty");
            this.grid.AddColumn("SystemByte");
            this.grid.AddColumn("TID");
            this.grid.AddColumn("Column1");
            this.grid.AddColumn("Column2");
            this.grid.AddColumn("Column3");
            this.grid.AddColumn("Column4");
            this.grid.AddColumn("Column5");
        }

        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.LineNumber.ToString().PadLeft(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 ] ----------------------------------------------------

        private StandardCollection Parsing()
        {
            try
            {
                this.tboxLog.Clear();
                this.tboxException.Clear();
                this.Collection.Clear();

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

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

                    string sourceFileName = lviewItem.Tag as string;
                    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(sourceFileName);
                        string destFileName = $@"{destPath}{System.IO.Path.GetFileName(sourceFileName)}";
                        System.IO.File.Copy(sourceFileName, destFileName, true);
                        sourceFileName = destFileName;
                    }

                    lstFileName.Add(sourceFileName);
                }   // Process Unit: File

                this.Parser.ModelID = this.tboxEqModelID.Text;
                this.Parser.SECSDefine = this.SECSDefine;
                this.Parser.Parsing(lstFileName.ToArray());
                this.Text = $"{strTitle} - Ver. {Application.ProductVersion}";
                this.tboxLog.Text = this.Parser.LogString.ToString();
                this.Collection.AddRange(this.Parser.StandardCollection);

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

        private LogFile[] LviewFiles_GetLogFile()
        {
            List<LogFile> lstFileNames = new List<LogFile>();
            foreach (ListViewItem item in this.lviewFiles.Items)
            {
                if (item.Tag != null && item.Tag.GetType() == typeof(string))
                {
                    LogFile logFile = new LogFile(item.Tag.ToString());
                    lstFileNames.Add(logFile);
                }
            }

            return lstFileNames.ToArray();
        }

        #endregion

    }

}
