using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections.Concurrent;
using System.IO.Compression;

using SystemX.Common;
using SystemX.Net.Platform.Common.ExtensionMethods;
using SystemX.Net.Platform.Common.Util;
using SystemX.Net.Platform.Common;
using SystemX.Net.XAdaptor.Manager;
using System.Net;
using System.Globalization;
using SystemX.Net.Comm.IIS_FTP;

namespace SystemX.Net.XAdaptor.PC.UI
{
    public partial class MainForm : Form
    {
        public enum eCurrentMode
        {
            Normal_Mode = 0,
            Debug_Mode = 1,
            User_Mode = 2
        }

        [Flags]
        public enum eModeAccess
        {
            Normal_Mode = 0x0001,
            Debug_Mode = 0x0002,
            User_Mode = 0x0004
        }

        private eModeAccess CurAccess { set; get; }

        private eCurrentMode CurMode { set; get; }

        private XAdaptorManager ManagerAdaptor;

        private bool[] bSocketState = new bool[3];

        DataSet dsReadXml;
        int iMaxPosition;
        int iReadPosition;
        DataTable dtReadXml;

        private BackgroundWorker IssueWorker;
        private Tuple<eResultIssued, string> IssuedResult;
        private string strIssueID;
        private string strIssueMacType;
        private bool bReIssue;

        private string strGetTestListInfo_ProdNoC = string.Empty;
        private string strGetTestListInfo_ProdNoP = string.Empty;
        private string strGetTestListInfo_TestCode = string.Empty;
        private string strGetTestListInfo_Gate1 = string.Empty;
        private string strGetTestListInfo_Gate2 = string.Empty;
        private string strGetTestListInfo_FileName = string.Empty;
        private string strGetTestListInfo_RegUserComment = string.Empty;
        private string strGetTestListInfo_Description = string.Empty;
        private string strGetTestListInfo_GroupName = string.Empty;
        private string strGetTestListInfo_ModelName = string.Empty;
        private string strGetTestListInfo_VariantNo = string.Empty;
        private string strGetTestListInfo_TestListNo = string.Empty;
        private string strGetTestListInfo_Config = string.Empty;
        private string strGetTestListInfo_TestType = string.Empty;
        private string strGetTestListInfo_Version = string.Empty;
        private string strGetTestListInfo_ProdCode = string.Empty;

        public ConcurrentQueue<string> SendWaitLogFile;

        private bool isHasRow(object obj)
        {
            if (obj is DataSet)
            {
                DataSet ds = null;
                ds = obj as DataSet;

                return ((ds != null) ? (ds.Tables.Cast<DataTable>().Any(table => table.Rows.Count != 0)) : false);

            }
            else
                return false;
        }

        public MainForm()
        {
            InitializeComponent();

            SendWaitLogFile = new ConcurrentQueue<string>();

            this.Size = new Size(660, 100);
            MainPanel.Size = new Size(644, 61);

            //CurAccess = eModeAccess.Normal_Mode | eModeAccess.User_Mode;
            CurAccess = eModeAccess.User_Mode | eModeAccess.Debug_Mode;

            //CurMode = eCurrentMode.Normal_Mode;

            //StartMode(eCurrentMode.Debug_Mode, true);
            StartMode(eCurrentMode.User_Mode, true);

            //string strNowTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox3.SelectedIndex = 0;
            comboBox4.SelectedIndex = 0;

            FMAFIcomboBox1.SelectedIndex = 0;
            RFIOMAcomboBox1.SelectedIndex = 0;

            ConsoleUtil.ConsoleHide();

            try
            {
                //TimeControl.DoSyncTime();

                ManagerAdaptor = new XAdaptorManager();

                string strGetConnectIP = ManagerAdaptor.GetAdaptorHandler.GetAdaptorConnectIP();
                string strGetHostID = ManagerAdaptor.GetAdaptorHandler.GetAdaptorHostID();
                string strGetSection = ManagerAdaptor.GetAdaptorHandler.GetAdaptorSection();
                string strGetTestCode = ManagerAdaptor.GetAdaptorHandler.GetAdaptorTestCode();
                int nCommandPort = ManagerAdaptor.GetAdaptorHandler.GetAdaptorCommandPort();
                int nStreamPort = ManagerAdaptor.GetAdaptorHandler.GetAdaptorStreamPort();
                bool bLoginResult = ManagerAdaptor.GetAdaptorHandler.GetAdaptorLoginResult();
                string strLoginMessage = ManagerAdaptor.GetAdaptorHandler.GetAdaptorLoginMessage();

                ManagerAdaptor.GetAdaptorHandler.CommandConnectAlarmEvent += ConnectCommandEvent;
                ManagerAdaptor.GetAdaptorHandler.StreamConnectAlarmEvent += ConnectStreamEvent;

                ManagerAdaptor.GetAdaptorHandler.ConnectionInfoRecvEvent += ConnectCommandInfoEvent;

                ManagerAdaptor.GetAdaptorHandler.CommandDisconnectAlarmEvent += DisconnectCommandEvent;
                ManagerAdaptor.GetAdaptorHandler.StreamDisconnectAlarmEvent += DisconnectStreamEvent;

                ManagerAdaptor.GetAdaptorHandler.LoginAlarmEvent += LoginEvent;

                //ManagerAdaptor.GetAdaptorHandler.QueryCallEvent += QueryRecvEvent;

                for (int i = 0; i < 2; i++)
                {

                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            if (ManagerAdaptor.CommandSocketConn == false ||
                ManagerAdaptor.StreamSocketConn == false)
            {
                Statelabel.Text = "DISCONNECT";
                Statelabel.ForeColor = Color.Red;
            }

            Statetimer.Enabled = true;
            AutoLogTimer.Enabled = true;

            IssueWorker = new BackgroundWorker();
            IssueWorker.WorkerReportsProgress = true;
            IssueWorker.WorkerSupportsCancellation = true;
            IssueWorker.DoWork += new DoWorkEventHandler(IssueWorkerDoWork);
            IssueWorker.ProgressChanged += new ProgressChangedEventHandler(IssueWorkerProgressChanged);
            IssueWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(IssueWorkerRunCompleted);
            IssuedResult = new Tuple<eResultIssued, string>(eResultIssued.None, "");
        }

        private void ConnectCommandEvent(object sender, EventArgs e)
        {
            bSocketState[0] = true;
        }

        private void ConnectStreamEvent(object sender, EventArgs e)
        {
            bSocketState[1] = true;
        }

        private void ConnectCommandInfoEvent(object sender, EventArgs e)
        {
            //if(ManagerAdaptor.GetAdaptorHandler.GetPortDistributionConnState == false)
                bSocketState[2] = true;
        }

        private void LoginEvent(object sender, EventArgs e)
        {
            bool bb1 = ManagerAdaptor.GetAdaptorHandler.GetAdaptorLoginResult();
            string ss2 = ManagerAdaptor.GetAdaptorHandler.GetAdaptorLoginMessage();
        }

        private void DisconnectCommandEvent(object sender, EventArgs e)
        {
            bSocketState[0] = false;
        }

        private void DisconnectStreamEvent(object sender, EventArgs e)
        {
            bSocketState[1] = false;
        }

        private void QueryRecvEvent(object sender, EventArgs e)
        {
            Invoke((MethodInvoker)delegate ()
            {
                if ((e as ResultEventArgs).bProcReuslt)
                {
                    dataGridView1.DataSource = ManagerAdaptor.GetTestListDataSet().Tables[0];
                }

                /*
                {
                    FieldInfo fld = typeof(CTest).GetField("aaa");
                    fld.SetValue(ctest, 66);
                }
                {
                    FieldInfo fld = typeof(CTest).GetField("bbb");
                    fld.SetValue(ctest, false);
                }
                */

                //TestList File
                /*
                if(isHasRow(sender))             
                {
                    int iCol1 = (sender as DataSet).Tables[0].Columns.IndexOf("TestListData");
                    int iCol2 = (sender as DataSet).Tables[0].Columns.IndexOf("FileName");
                    (sender as DataSet).Tables[0].Columns[iCol1].ColumnMapping = MappingType.Hidden;
                    dataGridView1.DataSource = (sender as DataSet).Tables[0];

                    byte[] ucGetTestListData = (sender as DataSet).Tables[0].Rows[0]["TestListData"] as byte[];
                    string strFileName = (sender as DataSet).Tables[0].Rows[0]["FileName"].ToString();
                    
                    string strVersion = (sender as DataSet).Tables[0].Rows[0]["Version"].ToString();
                    string ProdCode = (sender as DataSet).Tables[0].Rows[0]["ProdCode"].ToString();
                    string strExtension = ".CpXv" + strVersion + ProdCode;

                    //File.WriteAllBytes(@"C:\Users\SYSTEMX.KJH\Desktop\" + strFileName + strExtension, ucGetTestListData);
                }
                else
                    dataGridView1.DataSource = null;
                */

                /* 받아온 바이트 스트리임 이미지로 표시
                byte[] dd = null;
                if (((sender as DataSet) != null) ? (sender as DataSet).Tables.Cast<DataTable>().Any(table => table.Rows.Count != 0) : false)
                {
                    dd = (sender as DataSet).Tables[0].Rows[0]["LogData"] as byte[];
                }

                Guid uguid = Guid.NewGuid();

                string strTempFileName = @"D:\" + uguid.ToString("B") + ".jpg";

                try
                {
                    File.WriteAllBytes(strTempFileName, (byte[])dd);

                    using (FileStream fs = new FileStream(@strTempFileName, FileMode.Open, FileAccess.Read))
                    {
                        Image source = Image.FromStream(fs);

                        ;// pictureBox1.Image = source;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (File.Exists(strTempFileName))
                        File.Delete(strTempFileName);
                }
                */
            });
        }

        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
                this.Visible = false;
            else
                this.Visible = true;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("You want to program exit?", "XAdaptor", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                e.Cancel = true;
            else
                e.Cancel = false;
        }
       
        private bool CheckAccessLevel(eModeAccess ChkAccess)
        {
            if ((CurAccess & ChkAccess) == ChkAccess)
                return true;
            else
                return false;
        }

        private bool CheckLogin(bool bLoginPass = false)
        {
            if (bLoginPass == false)
            {
                LoginForm lf = new LoginForm();

                if (lf.ShowDialog() == DialogResult.OK)
                    return true;
                else
                    return false;
            }
            else
                return true;
        }

        private void StartMode(eCurrentMode SetMode, bool bLoginPass = false)
        {
           if(CheckLogin(bLoginPass))
            {
                switch(SetMode)
                {
                    case eCurrentMode.Normal_Mode:
                        MainPanel.Visible = true;

                        MainPanel.Dock = DockStyle.Fill;

                        this.MinimumSize = new Size(660, 100);
                        this.MaximumSize = new Size(660, 100);
                        break;
                    case eCurrentMode.Debug_Mode:
                        MainPanel.Dock = DockStyle.None;

                        this.MinimumSize = new Size(1500, 600);
                        this.MaximumSize = new Size(1500, 600);
                        break;
                    case eCurrentMode.User_Mode:
                        MainPanel.Dock = DockStyle.Fill;

                        this.MinimumSize = new Size(660, 240);
                        this.MaximumSize = new Size(660, 240);
                        break;
                }

                CurMode = SetMode;
            }
        }

        private void MainPanel_DoubleClick(object sender, EventArgs e)
        {
            if (CheckAccessLevel(eModeAccess.Debug_Mode))
            {
                if (DebugButton.Visible)
                    DebugButton.Visible = false;
                else
                    DebugButton.Visible = true;
            }
            //
            if (CheckAccessLevel(eModeAccess.User_Mode))
            {
                if (UserButton.Visible)
                    UserButton.Visible = false;
                else
                    UserButton.Visible = true;
            }
        }

        private void TestButton_Click(object sender, EventArgs e)
        {
            if (CheckAccessLevel(eModeAccess.Debug_Mode) == false)
                return;

            StartMode(eCurrentMode.Debug_Mode, false);

            DebugButton.Visible = false;
            UserButton.Visible = false;
        }

        private void UserButton_Click(object sender, EventArgs e)
        {
            if (CheckAccessLevel(eModeAccess.User_Mode) == false)
                return;

            StartMode(eCurrentMode.User_Mode, false);

            UserButton.Visible = false;
            DebugButton.Visible = false;
        }

        private void MainForm_DoubleClick(object sender, EventArgs e)
        {
            StartMode(eCurrentMode.Normal_Mode, true);
        }

        private void Statetimer_Tick(object sender, EventArgs e)
        {
            Statetimer.Enabled = false;

            //ManagerAdaptor.CheckStationTestListReload()
            //ManagerAdaptor.SetStationTestListReloadStateOff();

            /*foreach (int nStationID in ManagerAdaptor.NeedTestListReloadList())
            {
                if (ManagerAdaptor.GetStationTestListReload(nStationID))
                {
                    ManagerAdaptor.SetStationTestListReload(nStationID);

                    ManagerAdaptor.MgrConnection.QueryPRODReleaseList((uint)nStationID, QT_ProdcNoC_Info.Text,
                    QT_TestType_Info.Text,
                    QT_TestCode_Info.Text,
                    QT_TestListVersion_Info.Text,
                    QT_ProductionCode_Info.Text);
                }
            }*/

            if (ManagerAdaptor.GetAdaptorHandler.SubscribeConnectInfo.bSessionStarted)
            {
                double? dGetTimeOut = ManagerAdaptor.GetAdaptorHandler.GetSessionTimeoutTime();
                double dTimeOut = dGetTimeOut == null ? 300.0 : dGetTimeOut.Value;

                if (dTimeOut > 0.0)
                {
                    TimeSpan ts = ManagerAdaptor.GetAdaptorHandler.SubscribeConnectInfo.GetSessionTime();
                    SessionTimelabel.Text = ts.ToString(@"hh\:mm\:ss\.fffffff");

                    double dCurTime = 0.0;
                    int nPct = 0;

                    dCurTime = ts.TotalSeconds;
                    nPct = (int)((dCurTime * 100) / dTimeOut);

                    if (nPct < 0)
                        nPct = 0;
                    if (nPct > 100)
                        nPct = 100;

                    this.progressBar2.Value = nPct;
                }
            }

            string strMakeNotifyText = "XAdaptor-";
            string strMakeFormText = "XAdaptor-";

            if (bSocketState[0])
            {
                strMakeNotifyText += "[COMMAND ON]";
                strMakeFormText += "[COMMAND ON]";
            }
            else
            {
                strMakeNotifyText += "[COMMAND OFF]";
                strMakeFormText += "[COMMAND OFF]";
            }
            //
            if (bSocketState[1])
            {
                strMakeNotifyText += "[STREAM ON]";
                strMakeFormText += "[STREAM ON]";
            }
            else
            {
                strMakeNotifyText += "[STREAM OFF]";
                strMakeFormText += "[STREAM OFF]";
            }

            if (bSocketState[0] && bSocketState[1])
            {
                if (bSocketState[2])
                {
                    if (Statelabel.Text.CompareTo("CONNECT(RUNNING) ...") != 0)
                    {
                        Statelabel.Text = "CONNECT(RUNNING) ...";
                        Statelabel.ForeColor = Color.White;

                        if (UserConnectButton.Enabled)
                            UserConnectButton.Enabled = false;
                        if (UserDisconnectButton.Enabled == false)
                            UserDisconnectButton.Enabled = true;

                        if (CurMode == eCurrentMode.User_Mode)
                        {
                            this.MinimumSize = new Size(660, 560);
                            this.MaximumSize = new Size(660, 560);

                            if (groupBoxMacQuery.Visible == false)
                                groupBoxMacQuery.Visible = true;

                            progressBar2.Value = 0;
                        }
                    }
                }
                else
                {
                    if (Statelabel.Text.CompareTo("CONNECT") != 0)
                    {
                        Statelabel.Text = "CONNECT";
                        Statelabel.ForeColor = Color.LimeGreen;
                    }
                }
            }
            else
            {
                if (Statelabel.Text.CompareTo("DISCONNECT") != 0)
                {
                    Statelabel.Text = "DISCONNECT";
                    Statelabel.ForeColor = Color.Red;

                    if (ManagerAdaptor.GetAdaptorHandler.GetConnectionInfo.bPortDistribution == false ||
                        ManagerAdaptor.GetAdaptorHandler.SubscribeConnectInfo.bSubscriberClientResult == false)
                    {
                        if (UserConnectButton.Enabled == false)
                            UserConnectButton.Enabled = true;
                        if (UserDisconnectButton.Enabled)
                            UserDisconnectButton.Enabled = false;
                    }

                    if (CurMode == eCurrentMode.User_Mode)
                    {
                        if (groupBoxMacQuery.Visible)
                            groupBoxMacQuery.Visible = false;

                        this.MinimumSize = new Size(660, 240);
                        this.MaximumSize = new Size(660, 240);
                    }

                    bSocketState[2] = false;
                }
            }

            if (notifyIcon.Text.IndexOf(strMakeNotifyText) < 0)
                notifyIcon.Text = strMakeNotifyText;

            if (this.Text.IndexOf(strMakeFormText) < 0)
                this.Text = strMakeFormText;

            if (Statelabel.Text.CompareTo("CONNECT(RUNNING) ...") == 0)
            {
                if (Statelabel.ForeColor == Color.White)
                    Statelabel.ForeColor = Color.LimeGreen;
                else
                    Statelabel.ForeColor = Color.White;

                if (ManagerAdaptor.GetClientInfoState())
                {
                    LastCommandTimeLabel.Text = ManagerAdaptor.GetLastCommandTime().ToString();
                    LastStreamTimeLabel.Text = ManagerAdaptor.GetLastStreamTime().ToString();
                }
            }

            Statetimer.Enabled = true;
        }

        private async void AutoLogTimer_Tick(object sender, EventArgs e)
        {
            AutoLogTimer.Enabled = false;

            if (SendWaitLogFile.Count > 0)
            {
                string strGetFileName = string.Empty;
                if (SendWaitLogFile.TryDequeue(out strGetFileName))
                {
                    string strGetStationName = textBox16.Text;

                    var b1 = await ManagerAdaptor.MgrConn.AsyncCPLogFileTransfer(@strGetFileName,
                    strGetStationName,
                    int.Parse(strGetTestListInfo_TestListNo),
                    strGetTestListInfo_ProdNoP,
                    strGetTestListInfo_ProdNoC,
                    strGetTestListInfo_TestType,
                    strGetTestListInfo_TestCode,
                    strGetTestListInfo_Version,
                    strGetTestListInfo_ProdCode);
                }
            }

            AutoLogTimer.Enabled = true;
        }

        private void Statelabel_DoubleClick(object sender, EventArgs e)
        {
            ConsoleUtil.ConsoleVisibleControl();
        }

        private void contextMenuSubStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripItem tsi = e.ClickedItem;

            this.Close();
        }

        private async void button_QT_Click(object sender, EventArgs e)
        {
            uint nStationID = 0;

            if (uint.TryParse(textBox1.Text, out nStationID) == false)
                nStationID = 0;
            /*
            var getResult = await ManagerAdaptor.MgrConn.GetTestListQueryWithFilePath(@"D:\", nStationID, QT_ProdcNoC_Info.Text,
               QT_TestType_Info.Text,
               QT_TestCode_Info.Text,
               QT_TestListVersion_Info.Text,
               QT_ProductionCode_Info.Text);
            */

            //테스트리스트 파일경로
            //실패했을때는 string.empty 빈문자열
            //getResult.Item1
            //테스트리스트 번호
            //실패했을대는 int.MinValue
            //getResult.Item2

            /*var c2 = await ManagerAdaptor.MgrConn.GetTestListQueryWithFilePath(@"D:\", nStationID, QT_ProdcNoC_Info.Text,
               QT_TestType_Info.Text,
               QT_TestCode_Info.Text,
               QT_TestListVersion_Info.Text,
               QT_ProductionCode_Info.Text, true);*/

            var c2 = await ManagerAdaptor.MgrConn.GetTestListQueryWithFilePath(@"D:\", nStationID, QT_ProdcNoC_Info.Text,
              QT_TestType_Info.Text,
              QT_TestCode_Info.Text,
              QT_TestListVersion_Info.Text,
              QT_ProductionCode_Info.Text, false);

            if (c2.Item2 != int.MinValue)
            {
                dataGridView1.DataSource = ManagerAdaptor.GetTestListDataSet().Tables[0];
            }

            /*
            var b1 = await ManagerAdaptor.MgrConn.AsyncWaitCheckTestList(nStationID, QT_ProdcNoC_Info.Text,
               QT_TestType_Info.Text,
               QT_TestCode_Info.Text,
               QT_TestListVersion_Info.Text,
               QT_ProductionCode_Info.Text);

            if (b1)
            {
                var b2 = await ManagerAdaptor.MgrConn.AsyncWaitQueryTestList(nStationID, QT_ProdcNoC_Info.Text,
                    QT_TestType_Info.Text,
                    QT_TestCode_Info.Text,
                    QT_TestListVersion_Info.Text,
                    QT_ProductionCode_Info.Text);

                if (b2)
                    dataGridView1.DataSource = ManagerAdaptor.GetTestListDataSet().Tables[0];
            }
                */
        }
          
        private async void button18_Click(object sender, EventArgs e)
        {
            uint nStationID = 0;

            if (uint.TryParse(textBox1.Text, out nStationID) == false)
                nStationID = 0;

            var b = await ManagerAdaptor.MgrConn.AsyncWaitCheckTestList(nStationID, QT_ProdcNoC_Info.Text,
                QT_TestType_Info.Text,
                QT_TestCode_Info.Text,
                QT_TestListVersion_Info.Text,
                QT_ProductionCode_Info.Text);
        }


        private async void button19_Click(object sender, EventArgs e)
        {
            //bool b = ManagerAdaptor.CheckServerState();

            bool b1 = ManagerAdaptor.GetServerTestListLoadState();
            bool b2 = await ManagerAdaptor.AsyncWaitCheckServerState();
        }

        private void Button_FindInfo_Click(object sender, EventArgs e)
        {
            DataRow[] drs = ManagerAdaptor.GetTestListContainer().GetPRODTestList(QT_ProdNoP_Info.Text, QT_ProdcNoC_Info.Text,
                QT_TestType_Info.Text,
                QT_TestCode_Info.Text,
                QT_TestListVersion_Info.Text,
                QT_ProductionCode_Info.Text);

            if (drs != null && drs.Count() == 1)
            {
                DataTable dt = new DataTable();
                dt = drs.CopyToDataTable();
                int iCol1 = dt.Columns.IndexOf("TestListData");
                dt.Columns[iCol1].ColumnMapping = MappingType.Hidden;

                strGetTestListInfo_ProdNoC = drs[0]["ProdNo_C"].ToString();
                strGetTestListInfo_ProdNoP = drs[0]["ProdNo_P"].ToString();
                strGetTestListInfo_TestCode = drs[0]["TestCode"].ToString();
                strGetTestListInfo_Gate1 = drs[0]["Gate1"].ToString();
                strGetTestListInfo_Gate2 = drs[0]["Gate2"].ToString();
                strGetTestListInfo_FileName = drs[0]["FileName"].ToString();
                strGetTestListInfo_RegUserComment = drs[0]["RegUserComment"].ToString();
                strGetTestListInfo_Description = drs[0]["Description"].ToString();
                strGetTestListInfo_GroupName = drs[0]["GroupName"].ToString();
                strGetTestListInfo_ModelName = drs[0]["ModelName"].ToString();
                strGetTestListInfo_VariantNo = drs[0]["VariantNo"].ToString();
                strGetTestListInfo_TestListNo = drs[0]["TestListNo"].ToString();
                strGetTestListInfo_Config = drs[0]["Config"].ToString();
                strGetTestListInfo_TestType = drs[0]["TestType"].ToString();
                strGetTestListInfo_Version = drs[0]["Version"].ToString();
                strGetTestListInfo_ProdCode = drs[0]["ProdCode"].ToString();

                dataGridView1.DataSource = dt;

                Type type = typeof(QueryGetInfo);
                FieldInfo[] f = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                for (int i = 0; i < f.Length; i++)
                {
                    richTextBox1.AppendText(f[i].Name + " ");
                    richTextBox1.AppendText(f[i].GetValue(ManagerAdaptor.GetTestListContainer().ReadInfo()) + "\r\n");
                }

                label22.Text = ManagerAdaptor.GetTestListContainer().GetTestListCntID();

                string sss = ManagerAdaptor.GetTestListContainer().MakeTestListFile(@"D:\");

                dsReadXml = new DataSet();
                dsReadXml.ReadXml(sss);
                dtReadXml = new DataTable();

                iMaxPosition = dsReadXml.Tables.Count;
                iReadPosition = 0;
                dtReadXml = dsReadXml.Tables[iReadPosition];
                dataGridView2.DataSource = dtReadXml;
            }
            else
                dataGridView1.DataSource = null;

            /*
            if(xAdaptor.CurrentTestList().FindInfo(QT_TestType_Info.Text,
                QT_TestCode_Info.Text,
                QT_TestListVersion_Info.Text,
                QT_ProductionCode_Info.Text) != null)
                {
                    xAdaptor.CurrentTestList();
                }
            */
        }

        private void Button_List_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = ManagerAdaptor.GetTestListContainer().getTestListDataSet().Tables[0];
        }

        private void button2_Click(object sender, EventArgs e)
        {
            iReadPosition -= 1;

            if (iReadPosition < 0)
                iReadPosition = 0;

            dtReadXml = dsReadXml.Tables[iReadPosition];
            dataGridView2.DataSource = dtReadXml;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            iReadPosition += 1;

            if (iReadPosition >= iMaxPosition)
                iReadPosition = iMaxPosition - 1;

            dtReadXml = dsReadXml.Tables[iReadPosition];
            dataGridView2.DataSource = dtReadXml;
        }

        private async Task DoWorkAsync()
        {
            string strGetStationName = textBox16.Text;

            await Task.Delay(100);

            var b1 = await ManagerAdaptor.MgrConn.AsyncCPLogFileTransfer(@openFileDialog.FileName,
                        strGetStationName,
                        int.Parse(strGetTestListInfo_TestListNo),
                        strGetTestListInfo_ProdNoP,
                        strGetTestListInfo_ProdNoC,
                        strGetTestListInfo_TestType,
                        strGetTestListInfo_TestCode,
                        strGetTestListInfo_Version,
                        strGetTestListInfo_ProdCode);

            await Task.Delay(100);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stopwatch stSetTime = new Stopwatch();
                stSetTime.Start();

                string strGetStationName = textBox16.Text;

                //ManagerAdaptor.MgrConn.CPLogFileTransfer(@openFileDialog.FileName, "TEST", 0, "9101340064", "900134VTAU", "MMXX", "HT", "01", "e");

                /*var t = Task.Run(() =>
                {
                    ManagerAdaptor.MgrConn.CPLogFileTransfer(@openFileDialog.FileName,
                        strGetStationName,
                        int.Parse(strGetTestListInfo_TestListNo),
                        strGetTestListInfo_ProdNoP,
                        strGetTestListInfo_ProdNoC,
                        strGetTestListInfo_TestType,
                        strGetTestListInfo_TestCode,
                        strGetTestListInfo_Version,
                        strGetTestListInfo_ProdCode);
                });
                t.Wait();*/

                var task = DoWorkAsync();
                //task.Wait();
                task.ConfigureAwait(false);
                long ltime = stSetTime.ElapsedMilliseconds;
            }
        }

        private void button21_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string strSelectedPath = folderBrowserDialog.SelectedPath;

                string[] dirs = Directory.GetDirectories(strSelectedPath);
                string[] files = Directory.GetFiles(strSelectedPath, $"*.CpLog", SearchOption.TopDirectoryOnly);

                if (files.Length > 0)
                {
                    foreach (string f in files)
                    {
                        SendWaitLogFile.Enqueue(@f);
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                ManagerAdaptor.MgrConn.SendCustomFile(@openFileDialog.FileName);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;

            DataSet dsResult = ManagerAdaptor.MgrConn.WaitUserQuery(textBox2.Text);

            if (XCommons.isHasRow(dsResult))
                dataGridView1.DataSource = dsResult.Tables[0];
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (ManagerAdaptor.MgrUIMConn.CheckIssuedID(textBox3.Text) == eResultCheck.NotIssued)
                textBox3.BackColor = Color.Lime;
            else
                textBox3.BackColor = Color.Red;

        }

        private void button7_Click(object sender, EventArgs e)
        {
            eResultCheck rs = ManagerAdaptor.MgrUIMConn.CheckIssuedMacAddress(textBox4.Text);

            if(rs == eResultCheck.InvalidMacAddressFormat)
                textBox4.BackColor = Color.Red;
            else if (rs == eResultCheck.AlreadyIssued)
                textBox4.BackColor = Color.Yellow;
            else
                textBox4.BackColor = Color.Lime;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (ManagerAdaptor.MgrUIMConn.CheckListMacAddress(textBox5.Text))
                textBox5.BackColor = Color.Lime;
            else
                textBox5.BackColor = Color.Red;    
        }

        private void button9_Click(object sender, EventArgs e)
        {
            eMacAddressType type = eMacAddressType.InvalidMacAddressFormat;
            Enum.TryParse<eMacAddressType>(comboBox1.SelectedItem.ToString(), out type);

            if(type != eMacAddressType.InvalidMacAddressFormat)
                textBox6.Text = ManagerAdaptor.MgrUIMConn.GetToBeIssuedMacAddress(type);
        }

        private void button10_Click(object sender, EventArgs e)
        {
            label8.Text = ManagerAdaptor.MgrUIMConn.GetTotalAddressNumber().ToString();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            label9.Text = ManagerAdaptor.MgrUIMConn.GetCurrentIssuedAddressNumber().ToString();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            label10.Text = ManagerAdaptor.MgrUIMConn.GetRemainAddressNumber().ToString();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            textBox8.Text = ManagerAdaptor.MgrUIMConn.LookUpIDbyMacAddress(textBox7.Text);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            eMacAddressType type = eMacAddressType.InvalidMacAddressFormat;
            Enum.TryParse<eMacAddressType>(comboBox2.SelectedItem.ToString(), out type);

            eLookUpOption LookUp = eLookUpOption.CompareToSame;
            Enum.TryParse<eLookUpOption>(comboBox4.SelectedItem.ToString(), out LookUp);

            string strText = textBox9.Text;

            textBox10.Text = ManagerAdaptor.MgrUIMConn.LookUpMacAddressbyID(ref strText, LookUp, type);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            eMacAddressType type = eMacAddressType.InvalidMacAddressFormat;
            Enum.TryParse<eMacAddressType>(comboBox3.SelectedItem.ToString(), out type);

            string strGetMacAddressInfo = string.Empty;

            var vResult = ManagerAdaptor.MgrUIMConn.IssuanceRequest(textBox11.Text, checkBox1.Checked, type);

            textBox12.Text = vResult.strMacAddress;
            textBox15.Text = vResult.strErrMessage;

            if (vResult.eResult == eResultIssued.Success)
                textBox11.BackColor = Color.Lime;
            else
                textBox11.BackColor = Color.Red;
        }

        private async void button16_Click(object sender, EventArgs e)
        {
            ManagerAdaptor.GetAdaptorHandler.LoginID = textBox13.Text;
            ManagerAdaptor.GetAdaptorHandler.LoginKEY = textBox14.Text;

            ManagerAdaptor.WaitConnect();
        }

        private void button17_Click(object sender, EventArgs e)
        {
            ManagerAdaptor.Disconnect();
        }

        private async void UserConnectButton_Click(object sender, EventArgs e)
        {
            ManagerAdaptor.GetAdaptorHandler.LoginID = UserIDtextBox.Text;
            ManagerAdaptor.GetAdaptorHandler.LoginKEY = UserPasswordtextBox.Text;

            if (await ManagerAdaptor.Connect())
            {
                UserIDtextBox.Text = "";
                UserPasswordtextBox.Text = "";

                UserConnectButton.Enabled = false;

                if (ManagerAdaptor.CheckStateFTP() == eFTPServiceStatus.Connected)
                {
                    labelFTPConn.ForeColor = Color.LimeGreen;
                    labelFTPConn.Text = "FTP Connected";
                }
                else if (ManagerAdaptor.CheckStateFTP() == eFTPServiceStatus.Disconnected)
                {
                    labelFTPConn.Text = "FTP Failed";
                }
                else if (ManagerAdaptor.CheckStateFTP() == eFTPServiceStatus.Unused)
                {
                    labelFTPConn.ForeColor = Color.Yellow;
                    labelFTPConn.Text = "FTP Unused";
                }
            }
        }

        private void UserDisconnectButton_Click(object sender, EventArgs e)
        {
            ManagerAdaptor.Disconnect();
        }
        private void SessionTimelabel_DoubleClick(object sender, EventArgs e)
        {
            ManagerAdaptor.GetAdaptorHandler.SubscribeConnectInfo.SessionTimeSet();
        }

        private void FIFMABtn_Click(object sender, EventArgs e)
        {
            FIFMAtextBox2.Text = ManagerAdaptor.MgrUIMConn.LookUpIDbyMacAddress(FIFMAtextBox1.Text);
        }

        private void FMAFIBtn_Click(object sender, EventArgs e)
        {
            if (FMAFItextBox1.Text.Length <= 0)
                return;

            eMacAddressType type = eMacAddressType.InvalidMacAddressFormat;
            Enum.TryParse<eMacAddressType>(FMAFIcomboBox1.SelectedItem.ToString(), out type);

            string strText = FMAFItextBox1.Text;

            FMAFItextBox2.Text = ManagerAdaptor.MgrUIMConn.LookUpMacAddressbyID(ref strText, eLookUpOption.CompareToSame, type);
        }

        // Worker Thread가 실제 하는 일
        void IssueWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            DateTime dtTime = DateTime.Now;
            int nPct = 0;

            double? dGetWaitTime = ManagerAdaptor.GetAdaptorHandler.GetIssueWorkerWaitTime();
            double dWaitTime = dGetWaitTime == null ? 3000.0 : dGetWaitTime.Value;
            double dCurTime = 0.0;

            e.Result = null;

            while (IssueWorker.CancellationPending == false)
            {
                TimeSpan tsWait = DateTime.Now - dtTime;
                dCurTime = tsWait.TotalMilliseconds;
                nPct = (int)((dCurTime * 100) / dWaitTime);
                IssueWorker.ReportProgress(nPct);

                if (dCurTime >= dWaitTime)
                {
                    IssueWorker.ReportProgress(100);

                    Thread.Sleep(10);

                    break;
                }

                Thread.Sleep(10);
            }

            Thread.Sleep(100);

            if (IssueWorker.CancellationPending == false)
            {
                eMacAddressType type = eMacAddressType.InvalidMacAddressFormat;
                Enum.TryParse<eMacAddressType>(strIssueMacType, out type);

                string strGetMacAddressInfo = string.Empty;

                var vResult = ManagerAdaptor.MgrUIMConn.IssuanceRequest(strIssueID, bReIssue, type);

                e.Result = vResult;
            }
            else
                e.Cancel = true;
        }

        // Progress 리포트 - UI Thread
        void IssueWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int nGetValue = e.ProgressPercentage;

            if (nGetValue < 0)
                nGetValue = 0;
            if (nGetValue > 100)
                nGetValue = 100;

            this.progressBar1.Value = nGetValue;
        }

        // 작업 완료 - UI Thread
        void IssueWorkerRunCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            // 에러가 있는지 체크
            if (e.Error != null)
            {
                //MessageBox.Show(e.Error.Message, "Error");

                return;
            }
            else if(e.Cancelled)
            {
                this.progressBar1.Value = 0;
            }
            else
            {
                ResultIssued getResult = e.Result as ResultIssued;

                RFIOMAtextBox3.Text = getResult.strMacAddress;
                RFIOMAtextBox2.Text = getResult.strErrMessage;

                if (getResult.eResult == eResultIssued.Success)
                    RFIOMAtextBox1.BackColor = Color.Lime;
                else
                    RFIOMAtextBox1.BackColor = Color.Red;
            }

            RFIOMABtn.ForeColor = Color.Black;
            RFIOMABtn.Text = "Request for issuance of mac address";
            RFIOMABtn.Enabled = true;

            RFIOMAtextBox1.ReadOnly = false;
        }

        private void RFIOMABtn_Click(object sender, EventArgs e)
        {
            // 비동기(Async)로 실행 
            if (IssueWorker.IsBusy == false)
            {
                RFIOMAtextBox1.BackColor = Color.White;

                if (RFIOMAtextBox1.Text.Length <= 0)
                    return;

                if (MessageBox.Show("Do you really want to issue a MAC address for the ID [" + RFIOMAtextBox1.Text + "]? (Please check the ID again)", "XAdaptor", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                    return;

                strIssueID = RFIOMAtextBox1.Text;
                strIssueMacType = RFIOMAcomboBox1.SelectedItem.ToString();
                bReIssue = checkBox2.Checked;

                RFIOMAtextBox1.ReadOnly = true;

                RFIOMAtextBox3.Text = "";

                IssueWorker.RunWorkerAsync();

                RFIOMABtn.Text = "Cancellation of issuance";
                RFIOMABtn.ForeColor = Color.Red;
            }
            else
            {
                IssueWorker.CancelAsync();

                RFIOMABtn.Enabled = false;
            }
        }

        private async void button20_Click(object sender, EventArgs e)
        {
            if(await ManagerAdaptor.MgrConn.WaitSyncTimeServer(true))
            {
                int i = int.MaxValue;
            }    
        }
    }
}
