using DDUtilityApp.DATA;
using DDUtilityApp.LOGPARSER.DATA;
using JWH;
using JWH.NETWORK;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Telerik.WinControls.UI;

namespace DDUtilityApp.LOGPARSER
{

    public partial class FrmWorkFlow : Form
    {

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

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

        public EisEquipment Equipment { get; set; }

        #endregion

        #region [ FrmWorkFlow ] ------------------------------------------------

        public FrmWorkFlow()
        {
            InitializeComponent();

            this.SetLayout();
            this.SetEventHandler();
        }

        protected void SetLayout()
        {
            this.AllowDrop = true;

            if (GlobalVariable.Instance.WorkflowLocation == "Local") this.rbtnLocal.Checked = true;
            else this.rbtnRemote.Checked = true;
            this.tboxLocalPath.Text = GlobalVariable.Instance.WorkflowCompressPath;

            this.tboxWorkflow.Font = new Font("돋움체", 9.0f);
            this.tboxWorkflow.ScrollBars = ScrollBars.Both;
            this.tboxWorkflow.WordWrap = false;

            this.gridFile.TableElement.RowHeight = 20;
            //this.gridFile.AddColumn("ModelID");
            //this.gridFile.AddColumn("Version");
            this.gridFile.AddColumn("ModuleName");
            this.gridFile.AddColumn("Trigger");
            this.gridFile.AddColumn("Workflow");
            this.gridFile.AddColumn("Description");
            //this.gridFile.AddColumn("GemSettingID");
        }

        protected void SetEventHandler()
        {
            this.DragDrop += Control_DragDrop;
            this.DragEnter += Control_DragEnter;
            this.Load += FrmWorkFlow_Load;

            this.btnSelectFolder.Click += BtnSelectFolder_Click;
            this.btnOpenFolder.Click += BtnOpenFolder_Click;

            this.gridFile.CellDoubleClick += GridFile_CellDoubleClick;
            this.gridFile.DataBindingComplete += GridFile_DataBindingComplete;
        }

        private void FrmWorkFlow_Load(object sender, EventArgs e)
        {
            this.SetWorkflowFiles();
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F6:
                    this.gridFile.BestFitColumns(Telerik.WinControls.UI.BestFitColumnMode.DisplayedCells);
                    break;
            }

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

        #endregion

        #region [ Control Events ] --------------------------------------------

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

        private void Control_DragDrop(object sender, DragEventArgs e)
        {
            XLogger.Instance.Info(e);

            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            this.Download(files[0]);
        }

        private void BtnSelectFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.SelectedPath = this.tboxLocalPath.Text;
            if (dlg.ShowDialog() != DialogResult.OK) return;

            this.tboxLocalPath.Text =$@"{dlg.SelectedPath}\";
        }

        private void BtnOpenFolder_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.CompressInformation == null) return;
                Process.Start(this.CompressInformation.ExtractPath);
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void GridFile_CellDoubleClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            try
            {
                this.tboxWorkflow.Clear();
                if (this.CompressInformation == null) this.Download();
                if (this.CompressInformation == null) return;

                string fileName = e.Row.Cells[2].Value as string;
                foreach (FileInfo fileInfo in this.CompressInformation.Files)
                {
                    if (string.Compare(fileInfo.Name, fileName, true) == 0)
                    {
                        FileStream fileStream = fileInfo.OpenRead();
                        StreamReader reader = new StreamReader(fileStream);
                        this.tboxWorkflow.Text = reader.ReadToEnd();

                        reader.Close();
                        fileStream.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex);
            }
        }

        private void GridFile_DataBindingComplete(object sender, GridViewBindingCompleteEventArgs e)
        {
            this.gridFile.BestFitColumns(BestFitColumnMode.DisplayedCells);
        }

        #endregion

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

        private void SetWorkflowFiles()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"SELECT  * ");
            sb.AppendLine($"FROM    WorkflowMapping ");
            sb.AppendLine($"WHERE   ModelID = '{this.Equipment.ModelID}' ");
            sb.AppendLine($"        AND Version = '{this.Equipment.RunningVersion}' ");
            sb.AppendLine($"        AND Workflow IS NOT NULL ");
            sb.AppendLine($"ORDER BY ModuleName, 'Trigger', Workflow ");
            DataSet ds = this.Equipment.Server.ExecuteQuery(sb.ToString());

            this.gridFile.DataSource = ds.Tables[0];
            this.gridFile.GroupDescriptors.Add(new GridGroupByExpression(this.gridFile.Columns[0]));
        }

        private void Download(string path = "")
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                string downFullName = $@"{GlobalVariable.Instance.WorkflowPath}{this.Equipment.ModelID}_{this.Equipment.RunningVersion}.Compress";

                if (string.IsNullOrEmpty(path))
                {
                    if (this.rbtnLocal.Checked)
                    {
                        path = $"{this.tboxLocalPath.Text}/{this.Equipment.ModelID}/{this.Equipment.RunningVersion}/ALL.COMPRESS";
                        System.IO.File.Copy(path, downFullName, true);
                    }
                    else
                    {
                        string uri = $"ftp://{this.Equipment.Server.FTPAddress}:{this.Equipment.Server.FTPPort}/";
                        string uid = this.Equipment.Server.FTPUserID;
                        string pwd = this.Equipment.Server.FTPPassword;
                        path = $"{this.Equipment.ModelID}/{this.Equipment.RunningVersion}";

                        FtpClient client = new FtpClient(uri, uid, pwd);
                        string[] lstName = client.GetList(path);
                        string fullName = string.Empty;
                        foreach (string name in lstName)
                        {
                            if (string.Compare(name, $"ALL.COMPRESS", true) == 0)
                            {
                                fullName = name;
                                break;
                            }
                        }
                        if (string.IsNullOrEmpty(fullName)) return;

                        bool result = client.Download($"{path}/ALL.COMPRESS", downFullName);
                        if (result == false) return;
                    }
                }
                else
                {
                    downFullName = $@"{GlobalVariable.Instance.WorkflowPath}{System.IO.Path.GetFileName(path)}";
                    System.IO.File.Copy(path, downFullName, true);
                }

                this.CompressInformation = new CompressInformation(downFullName);
                if (this.rbtnLocal.Checked)
                {
                    GlobalVariable.Instance.WorkflowLocation = "Local";
                    if (!string.IsNullOrEmpty(this.tboxLocalPath.Text)) GlobalVariable.Instance.WorkflowCompressPath = this.tboxLocalPath.Text;
                }
                else
                {
                    GlobalVariable.Instance.WorkflowLocation = "Remote";
                }
            }
            catch (Exception ex)
            {
                XLogger.Instance.Fatal(ex, true);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        #endregion


    }

}
