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

namespace DDUtilityApp.LOGPARSER
{

    public partial class FrmLogParser01 : Form
    {

        private Font RadGridFont = new Font(new FontFamily("돋움체"), 11.0f);

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

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

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

        private string WindowText { get; set; } = $"[EverOne MCS] LOG File Viewer";

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

            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.tboxException.WordWrap = false;
            this.tboxException.Font = new Font("돋움체", 9);

            this.lviewFiles.View = View.Details;
            ColumnHeader header = this.lviewFiles.Columns.Add("File Name");
            this.lviewFiles.CheckBoxes = true;
            this.lviewFiles.MultiSelect = false;
            this.lviewFiles.Sorting = SortOrder.Ascending;
            this.lviewFiles.ListViewItemSorter = new ListViewItemComparer(0, this.lviewFiles.Sorting);

            this.RadGrid_Setting();
        }

        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.tboxFilename.KeyDown += TboxFilename_KeyDown;
            this.btnFileAdd.Click += BtnFileAdd_Click;
            this.btnFileRemove.Click += BtnFileRemove_Click;
            this.btnClear.Click += BtnFileClear_Click;
            this.btnParsing.Click += BtnParsing_Click;

            // Option
            this.btnClearFilter.Click += BtnClearFilter_Click;
            this.btnColumnResize.Click += BtnColumnResize_Click;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                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.BtnColumnResize_Click(this.btnColumnResize, new EventArgs());
                    break;
            }

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

        #region [ DragDrop ] --------------------------------------------------

        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.BtnParsing_Click(this.btnParsing, new EventArgs());
        }

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

        #endregion

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

        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;
                    this.tboxFilename.Focus();
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void LviewFiles_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            try
            {
                SortOrder sorting = SortOrder.None;
                switch (this.lviewFiles.Sorting)
                {
                    case SortOrder.None:
                        sorting = SortOrder.Ascending;
                        break;
                    case SortOrder.Ascending:
                        sorting = SortOrder.Descending;
                        break;
                    case SortOrder.Descending:
                        sorting = 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 TboxFilename_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                this.BtnFileAdd_Click(this.btnFileAdd, new EventArgs());
        }

        private void BtnFileAdd_Click(object sender, EventArgs e)
        {
            try
            {
                ListViewItem lviewItem = this.lviewFiles.Items.Add(Path.GetFileName(this.tboxFilename.Text));
                lviewItem.Checked = true;
                lviewItem.Tag = this.tboxFilename.Text;
            }
            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;

                this.Parsing();

                if (this.chkFilterLinktest.Checked)
                    this.grid.DataSource = this.Collection.Where(item => item.Column1 != "LINKTEST");
                else
                    this.grid.DataSource = this.Collection;
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        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);
            //foreach (GridViewColumn column in this.grid.Columns)
            //{
            //    if (column.Name.ToUpper().StartsWith("COLUMN")) column.Width = 100;
            //    if (new string[] { "TID" }.Contains(column.Name.ToUpper())) column.Width = 100;
            //}
        }


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

        #endregion

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

        private void RadGrid_Setting()
        {
            this.grid.Columns.Clear();
            if (this.grid.GetType() == typeof(RadGridView))
            {
                RadGridView rgrid = this.grid as RadGridView;
                rgrid.Font = this.RadGridFont;
                rgrid.AllowAddNewRow = false;
                rgrid.AddNewRowPosition = SystemRowPosition.Top;
                rgrid.NewRowEnterKeyMode = RadGridViewNewRowEnterKeyMode.EnterMovesToLastAddedRow;
                rgrid.SelectionMode = GridViewSelectionMode.FullRowSelect;
                rgrid.AllowAutoSizeColumns = false;
                rgrid.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.None;
                rgrid.EnableFiltering = true;
                rgrid.ShowFilteringRow = false;
                rgrid.ShowHeaderCellButtons = true;
                rgrid.ShowNoDataText = true;
                rgrid.ShowRowErrors = true;
                rgrid.ShowGroupedColumns = true;
                rgrid.ShowGroupPanelScrollbars = true;
                rgrid.AllowEditRow = false;
                rgrid.TableElement.RowHeaderColumnWidth = 80;

                rgrid.DataBindingComplete += RadGrid_DataBindingComplete;
                rgrid.SelectionChanged += RadGrid_SelectionChanged;
                rgrid.ViewCellFormatting += RadGrid_ViewCellFormatting;
                rgrid.CellDoubleClick += RadGrid_CellDoubleClick;
                rgrid.KeyDown += RadGrid_KeyDown;
                rgrid.KeyUp += RadGrid_KeyUp;
                rgrid.CellClick += RadGrid_CellClick;
            }
        }

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

        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;

                List<BaseFormattingObject> lstFormat = new List<BaseFormattingObject>();
                foreach (GridViewDataColumn column in rgrid.Columns)
                {
                    lstFormat.Clear();
                    foreach (BaseFormattingObject obj in column.ConditionalFormattingObjectList)
                    {
                        if (new string[] { "Level_Error", "Type_Error", "Server_Error", "Return_1" }.Contains(obj.Name)) continue;
                        lstFormat.Add(obj);
                    }

                    foreach (BaseFormattingObject obj in lstFormat)
                        column.ConditionalFormattingObjectList.Remove(obj);
                }

                var value = e.Value;
                //DateTime column Convert
                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


                e.CellElement.TextImageRelation = TextImageRelation.ImageBeforeText;
            }
            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"))
            {
                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"))
            {
                //rgrid.Columns["Type"].TextAlignment = ContentAlignment.MiddleCenter;
                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"))
            {
                rgrid.Columns["Return"].TextAlignment = ContentAlignment.MiddleCenter;
                ExpressionFormattingObject formatting = new ExpressionFormattingObject($"Return_1", "Return<>0", true);
                formatting.RowBackColor = Color.FromArgb(128, 255, 0, 0);
                rgrid.Columns["Return"].ConditionalFormattingObjectList.Add(formatting);
            }

            //if (this.chkFilterLinktest.Checked)
            //{
            //    FilterDescriptor filter = new FilterDescriptor("Column1", FilterOperator.IsNotEqualTo, "LINKTEST");
            //    filter.IsFilterEditor = true;
            //    this.grid.FilterDescriptors.Add(filter);
            //}

            rgrid.BestFitColumns(BestFitColumnMode.DisplayedCells);
        }

        private void RadGrid_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                RadGridView rgrid = sender as RadGridView;
                if (rgrid == null) 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();
            }
        }

        #endregion

        private StandardCollection Parsing()
        {
            try
            {
                this.tboxLog.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 = $@"{Application.StartupPath}\Download";
                        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

                EisParser logParser = new EisParser(lstFileName.ToArray());
                logParser.Parsing();

                this.Text = $"{strTitle} - Ver. {Application.ProductVersion}";
                this.tboxLog.Text = logParser.LogString.ToString();
                this.Collection.AddRange(logParser.StandardCollection);

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

    }

}
