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

using SystemX.Common.Archive;
using SystemX.Product.ALIS.UI.Subs;
using SystemX.Product.ALIS.UI.View.InfoList;
using SystemX.Product.ALIS.Interface;

using static SystemX.Product.ALIS.UI.View.ViewCfg;
using static SystemX.Product.ALIS.UI.Commons;
using static SystemX.Net.Platform.Common.Util.LogMessage;

using CpTesterPlatform.CpLogUtil;
using CpApplication;
using CpApplication.Manager;
using CpCommon;

using PsKGaudi.Parser.PsCCSArea;
using PsKGaudi;
using PsKGaudi.Parser.MacroModuleSkel;
using PsKGaudi.Parser.PsCCSSTDFn.Parameters;
using PsKGaudi.Parser.PsCCSSTDFn;

using static PsCommon.PsCommon;
using static CpCommon.ExceptionHandler;
using static PsKGaudi.Parser.PsCCS;

using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using SystemX.Common;

namespace SystemX.Product.ALIS.UI.View.InfoList
{
    //* FOR TEST
    public class MergedRowsHelper
    {
        List<int> _rows = new List<int>();

        GridView _gridView;

        public void Register(GridView gridView)
        {
            if (gridView == null) return;

            _gridView = gridView;

            gridView.FocusedRowChanged += gridView_FocusedRowChanged;
            gridView.RowStyle += gridView_RowStyle;
            gridView.GridControl.Load += GridControl_Load;
        }

        void GridControl_Load(object sender, EventArgs e)
        {
            RefreshMergedRows();
        }

        void gridView_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (_rows.Contains(_gridView.GetDataSourceRowIndex(e.RowHandle)))
            {
                e.Appearance.Assign(_gridView.PaintAppearance.FocusedRow);

                e.HighPriority = true;
            }
        }

        void gridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            RefreshMergedRows();
        }

        void RefreshMergedRows()
        {
            _rows = GetMergedRows(_gridView.FocusedRowHandle);

            _gridView.RefreshData();
        }

        List<int> GetMergedRows(int rowHandle)
        {
            HashSet<int> mergedRows = new HashSet<int>();
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in _gridView.VisibleColumns)
            {
                var originalCell = _gridView.GetRowCellDisplayText(rowHandle, col);
                for (int i = rowHandle; ; i--)
                {
                    if (!_gridView.IsValidRowHandle(i)) break;
                    var cell = _gridView.GetRowCellDisplayText(i, col);
                    if (cell == originalCell) mergedRows.Add(i);
                    else break;
                }
                for (int i = rowHandle; ; i++)
                {
                    if (!_gridView.IsValidRowHandle(i)) break;
                    var cell = _gridView.GetRowCellDisplayText(i, col);
                    if (cell == originalCell) mergedRows.Add(i);
                    else break;
                }
            }
            List<int> result = new List<int>();
            foreach (var item in mergedRows)
            {
                result.Add(_gridView.GetDataSourceRowIndex(item));
            }
            return result;
        }

    }

    public partial class UcTestListView
    {
        private bool LoginStateCheck()
        {
            return ViewLoginState;
        }

        private bool CheckSelectedData()
        {
            if (SelectOpenType == eSelectType.TestListFile)
                return SelectTestListFileInfo.bHasSelectedData;
            else if (SelectOpenType == eSelectType.TestListVariant)
                return SelectTestListVariantInfo.bHasSelectedData;
            else if (SelectOpenType == eSelectType.TestListRelease)
                return SelectTestListReleaseInfo.bHasSelectedData;
            else
                return false;
        }

        private bool MainViewModeCheckErr()
        {
            if (eNowViewMode != eSetViewMode.MainView)
            {
                MessageBox.Show("Change the view state to the Main View(PROD_Variant), that is, the PROD Variant View state.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return true;
            }

            return false;
        }

        private bool SubViewModeCheckErr()
        {
            if (eNowViewMode != eSetViewMode.SubView)
            {
                MessageBox.Show("Change the view state to the Sub View(VRFY_TestListFileRelease), that is, the VRFY Release View state.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return true;
            }

            return false;
        }

        private bool SelectedRowCheckErr()
        {
            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
            {
                MessageBox.Show("Click the [No] column of the row you want.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return true;
            }

            return false;
        }

        private int TestListNoCheckErr()
        {
            int iSetTestListNo = Convert.ToInt32(nVRFYParameter);

            if (iSetTestListNo < 0)
            {
                MessageBox.Show("Click the " + strSelectTable + " [No] column of the row after use.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return int.MinValue;
            }

            return iSetTestListNo;
        }

        private void NewItem()
        {
            if (LoginStateCheck() == false) return;
            if (MainViewModeCheckErr()) return;

            DialogResult getResult = new DialogResult();
            getResult = DialogResult.None;

            eEdtType = eEditType.Insert;

            switch (SelectOpenType)
            {
                case eSelectType.TestListFile:
                    SelectTestListFileInfo.RegDT = ctrlDB.GetServerDateTime();
                    SelectTestListFileInfo.RegUser = ctrlDB.GetLoginInfo().UserID;
                    SelectTestListFileInfo.UpdateDT = ctrlDB.GetServerDateTime();
                    SelectTestListFileInfo.UpdateUser = ctrlDB.GetLoginInfo().UserID;

                    TestListFileInfoEdit CtrlTestListFileinfo = new TestListFileInfoEdit(ctrlDB, TestListFileInfoEdit.eSelectMode.Insert, SelectTestListFileInfo);
                    SetObjectPosition(CtrlTestListFileinfo);

                    EventClear(CtrlTestListFileinfo);
                    WizardCancelEvent += CtrlTestListFileinfo.WizardCancelEvent;

                    CtrlTestListFileinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListFileinfo.ShowDialog();
                    if (getResult == DialogResult.OK)
                    {
                        SetTestListFileFieldInfo();

                        InsertProdTestListFileInformation(SelectTestListFileInfo);

                        SelectTestListFileInfo.SelectTestListFileNo = GetProdTestListFileNoFind(SelectTestListFileInfo);
                    }
                    break;
                case eSelectType.TestListVariant:
                    SelectTestListVariantInfo.RegDT = ctrlDB.GetServerDateTime();
                    SelectTestListVariantInfo.RegUser = ctrlDB.GetLoginInfo().UserID;
                    SelectTestListVariantInfo.UpdateDT = ctrlDB.GetServerDateTime();
                    SelectTestListVariantInfo.UpdateUser = ctrlDB.GetLoginInfo().UserID;

                    TestListVariantInfoEdit CtrlTestListVariantinfo = new TestListVariantInfoEdit(ctrlDB, TestListVariantInfoEdit.eSelectMode.Insert, SelectTestListVariantInfo);
                    SetObjectPosition(CtrlTestListVariantinfo);

                    EventClear(CtrlTestListVariantinfo);
                    WizardCancelEvent += CtrlTestListVariantinfo.WizardCancelEvent;

                    CtrlTestListVariantinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListVariantinfo.ShowDialog();
                    if (getResult == DialogResult.OK)
                    {
                        SetTestListVariantFieldInfo();

                        InsertProdTestListVariantInformation(SelectTestListVariantInfo);

                        SelectTestListVariantInfo.SelectVariantNo = GetProdTestListVariantNoFind(SelectTestListVariantInfo);
                    }
                    break;
                case eSelectType.TestListRelease:
                    SelectTestListReleaseInfo.RegDT = ctrlDB.GetServerDateTime(); //DateTime.Now;
                    SelectTestListReleaseInfo.RegUser = ctrlDB.GetLoginInfo().UserID;

                    TestListInfoReleaseEdit CtrlTestListReleaseinfo = new TestListInfoReleaseEdit(ctrlDB, TestListInfoReleaseEdit.eSelectMode.Insert, SelectTestListReleaseInfo);
                    SetObjectPosition(CtrlTestListReleaseinfo);

                    EventClear(CtrlTestListReleaseinfo);
                    WizardCancelEvent += CtrlTestListReleaseinfo.WizardCancelEvent;

                    CtrlTestListReleaseinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListReleaseinfo.ShowDialog();

                    if (getResult == DialogResult.OK)
                        InsertReleaseListInformation(SelectTestListReleaseInfo);

                    break;
                default:
                    break;
            }

            if (getResult == DialogResult.OK)
            {
                if (SelectOpenType == eSelectType.TestListFile)
                    RunAsyncFileInsertUpdateWorker();
                else if (SelectOpenType == eSelectType.TestListVariant)
                    RunAsyncVariantInsertUpdateWorker();

                ViewRefresh();
            }
        }

        private void ModifyItem()
        {
            if (LoginStateCheck() == false) return;
            if (MainViewModeCheckErr()) return;
            if (SelectedRowCheckErr()) return;

            DialogResult getResult = new DialogResult();
            getResult = DialogResult.None;

            SqlCommand cmd = new SqlCommand();

            string sqlCommandText = "";
            string columns = string.Empty;

            eEdtType = eEditType.Modify;

            bool bResult = CreateInfo(SelectOpenType);

            if (bResult == false)
                return;

            switch (SelectOpenType)
            {
                case eSelectType.TestListFile:
                    TestListFileInfoEdit CtrlTestListFileinfo = new TestListFileInfoEdit(ctrlDB, TestListFileInfoEdit.eSelectMode.Modify, SelectTestListFileInfo);
                    SetObjectPosition(CtrlTestListFileinfo);

                    EventClear(CtrlTestListFileinfo);
                    WizardCancelEvent += CtrlTestListFileinfo.WizardCancelEvent;

                    CtrlTestListFileinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListFileinfo.ShowDialog();

                    if (getResult == DialogResult.OK)
                        SetTestListFileFieldInfo();
                    break;
                case eSelectType.TestListVariant:
                    TestListVariantInfoEdit CtrlTestListVariantinfo = new TestListVariantInfoEdit(ctrlDB, TestListVariantInfoEdit.eSelectMode.Modify, SelectTestListVariantInfo);
                    SetObjectPosition(CtrlTestListVariantinfo);

                    EventClear(CtrlTestListVariantinfo);
                    WizardCancelEvent += CtrlTestListVariantinfo.WizardCancelEvent;

                    CtrlTestListVariantinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListVariantinfo.ShowDialog();

                    if (getResult == DialogResult.OK)
                    {
                        SetTestListVariantFieldInfo();

                        //SelectTestListVariantInfo.PROD_TestListNo = getProdTestListNoFind(SelectTestListVariantInfo);
                    }
                    break;
                case eSelectType.TestListRelease:
                    TestListInfoReleaseEdit CtrlTestListReleaseinfo = new TestListInfoReleaseEdit(ctrlDB, TestListInfoReleaseEdit.eSelectMode.Modify, SelectTestListReleaseInfo);
                    SetObjectPosition(CtrlTestListReleaseinfo);

                    EventClear(CtrlTestListReleaseinfo);
                    WizardCancelEvent += CtrlTestListReleaseinfo.WizardCancelEvent;

                    CtrlTestListReleaseinfo.StartPosition = FormStartPosition.CenterParent;

                    getResult = CtrlTestListReleaseinfo.ShowDialog();
                    if (getResult == DialogResult.OK)
                    {
                        SetTestListRelFieldInfo();

                        columns = "ProdNo_C,TestCodeNo,VariantNo,Config,RegDT,RegUser,RegUserComment";

                        Type type = typeof(CReleaseInformation);
                        FieldInfo[] f = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                        sqlCommandText = "UPDATE PROD_Release SET ";
                        foreach (string str in columns.Split(','))
                        {
                            int idx = -1;
                            idx = Array.FindIndex(f, x => x.Name.IndexOf(str) >= 0);

                            if (str == "RegDT" || str == "UpdateDT")
                            {
                                string strGetDateTime = ctrlDB.SetConvertDateTime(f[idx].GetValue(SelectTestListReleaseInfo).ToString());
                                sqlCommandText += str + " = '" + strGetDateTime + "', ";
                            }
                            else
                                sqlCommandText += str + " = '" + f[idx].GetValue(SelectTestListReleaseInfo) + "', ";
                        }

                        sqlCommandText = sqlCommandText.Remove(sqlCommandText.Length - 2, 1);
                        sqlCommandText += "WHERE No = " + AbsoluteUniqueNo + ";";

                        cmd = new SqlCommand(sqlCommandText, ctrlDB.GetConnSqlCmd().Connection);

                        int EffectRows = cmd.ExecuteNonQuery();
                    }
                    break;
                default:
                    break;
            }

            if (getResult == DialogResult.OK)
            {
                if (SelectOpenType == eSelectType.TestListFile)
                    RunAsyncFileInsertUpdateWorker();
                else if (SelectOpenType == eSelectType.TestListVariant)
                    RunAsyncVariantInsertUpdateWorker();

                ViewRefresh();
            }
        }

        private void DeleteCommandSet(ref string[] strDeleteProcCommand, ref string[] strDeleteProcSubCommand)
        {
            for (int i = 0; i < strDeleteProcCommand.Length; i++)
            {
                strDeleteProcCommand[i] = string.Empty;
                strDeleteProcSubCommand[i] = string.Empty;
            }

            switch (SelectOpenType)
            {
                case eSelectType.TestListFile:
                    {
                        strDeleteProcCommand[0] = "DELETE [HIST_TestListFile] WHERE TestlistFileNo = !@#$%Number!@#$%;";
                        strDeleteProcCommand[1] = "DELETE [VRFY_TestListFileRelease] WHERE TestlistFileNo = !@#$%Number!@#$%;";
                        strDeleteProcCommand[2] = "DELETE [HIST_TestListFileLatestStepVersion] WHERE TestlistFileNo = !@#$%Number!@#$%";
                        strDeleteProcCommand[3] = "DELETE [HIST_TestListFileVariantList] WHERE TestlistFileNo = !@#$%Number!@#$%;";

                        strDeleteProcCommand[4] = "DELETE [STOR_TestListFile] WHERE No = !@#$%Number!@#$%;";

                        strDeleteProcSubCommand[0] = "DELETE [HIST_TestListFile] WHERE TestlistFileNo IS NULL;";
                        strDeleteProcSubCommand[1] = "DELETE [VRFY_TestListFileRelease] WHERE TestlistFileNo IS NULL;";
                        strDeleteProcSubCommand[2] = "DELETE [HIST_TestListFileLatestStepVersion] WHERE TestlistFileNo IS NULL;";
                        strDeleteProcSubCommand[3] = "DELETE [HIST_TestListFileVariantList] WHERE TestlistFileNo IS NULL;";
                    }
                    break;
                case eSelectType.TestListVariant:
                    strDeleteProcCommand[0] = "DELETE [PROD_Variant] WHERE No = !@#$%Number!@#$%;";
                    break;
                case eSelectType.TestListRelease:
                    strDeleteProcCommand[0] = "DELETE [PROD_Release] WHERE No = !@#$%Number!@#$%;";
                    break;
            }
        }

        private void DeleteItem()
        {
            if (LoginStateCheck() == false) return;

            string strTitle = SelectOpenType.ToString();

            int[] getSelectRows = gridHistView.GetSelectedRows();
            int nSelectedSize = gridHistView.SelectedRowsCount;

            string[] strSetDeleteName1 = new string[nSelectedSize];
            string[] strSetDeleteName2 = new string[nSelectedSize];
            int[] nSetDeleteNo = new int[nSelectedSize];

            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
                return;

            string strAlarmText = string.Empty;

            try
            {
                strAlarmText = "Are you sure you want to delete the <" + strTitle + ">\r\n";

                for (int i = 0; i < nSelectedSize; i++)
                {
                    DataRow dr = gridHistView.GetDataRow(getSelectRows[i]);

                    nSetDeleteNo[i] = Convert.ToInt32(dr["No"].ToString());

                    switch (SelectOpenType)
                    {
                        case eSelectType.TestListFile:
                            /*
                            strSetDeleteName1[i] = dr["Name"].ToString();
                            strSetDeleteName2[i] = dr["FileName"].ToString();
                            */
                            strSetDeleteName1[i] = dr["FileName"].ToString();
                            strSetDeleteName2[i] = dr["FileVersion"].ToString();
                            break;
                        case eSelectType.TestListVariant:
                            strSetDeleteName1[i] = dr["P_ProdNo"].ToString();
                            strSetDeleteName2[i] = dr["FileName"].ToString();
                            break;
                        case eSelectType.TestListRelease:
                            strSetDeleteName1[i] = dr["C_ProdNo"].ToString();
                            strSetDeleteName2[i] = dr["P_ProdNo"].ToString();
                            break;
                    }

                    //AbsoluteHostName
                    strAlarmText += "[" + nSetDeleteNo[i].ToString() + "][" + strSetDeleteName1[i] + "][" + strSetDeleteName2[i] + "] \r\n";
                }

                strAlarmText += "information?";
            }
            catch (Exception ex)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" " + SelectOpenType.ToString() + " Data Delete Error[1] " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);

                return;
            }

            if (MessageBox.Show(strAlarmText, strTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string[] strDeleteProcCommand = new string[10];
                string[] strDeleteProcSubCommand = new string[10];

                for (int i = 0; i < nSelectedSize; i++)
                {
                    DeleteCommandSet(ref strDeleteProcCommand, ref strDeleteProcSubCommand);

                    for (int j = 0; j < strDeleteProcCommand.Length; j++)
                    {
                        if (strDeleteProcCommand[j] != string.Empty)
                        {
                            strDeleteProcCommand[j] = strDeleteProcCommand[j].Replace("!@#$%Number!@#$%", nSetDeleteNo[i].ToString());

                            ctrlDB.GetConnSqlCmd().CommandText = strDeleteProcCommand[j];

                            try
                            {
                                int EffectRows = ctrlDB.GetConnSqlCmd().ExecuteNonQuery();
                            }
                            catch (Exception ex)
                            {
                                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" " + SelectOpenType.ToString() + " Data Delete Error[2] Main Command Error " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
                            }

                            Thread.Sleep(50);
                        }
                    }
                }
                //
                for (int i = 0; i < strDeleteProcSubCommand.Length; i++)
                {
                    if (strDeleteProcSubCommand[i] != string.Empty)
                    {
                        ctrlDB.GetConnSqlCmd().CommandText = strDeleteProcSubCommand[i];

                        try
                        {
                            int EffectRows = ctrlDB.GetConnSqlCmd().ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @" " + SelectOpenType.ToString() + " Data Delete Error[3] Sub Command Error " + ex.Message, ConsoleColor.Red, LogMessageLevel.FATAL);
                        }

                        Thread.Sleep(50);
                    }
                }

                ViewRefresh();

                ClearListSelect();
            }
        }

        private void ClearListSelect()
        {
            simpleLabelItemSelectRow.Text = "-";
            //simpleLabelItemSelectCol.Text = "-";

            AbsoluteIndexRow = -1;
            //AbsoluteIndexCol = -1;

            AbsoluteUniqueNo = "";

            nVRFYParameter = -1;
        }

        private void FilterMode(bool bFilterModeDoOff = false)
        {
            if (LoginStateCheck() == false) return;

            if (gridHistView.Columns.Count <= 0)
                return;

            int[] nFilterIdx = null;

            try
            {
                gridHistView.BeginUpdate();

                if (SelectOpenType == eSelectType.TestListFile)
                    nFilterIdx = null;
                else if (SelectOpenType == eSelectType.TestListVariant)
                    nFilterIdx = new int[2] { 1, 3 };
                else if (SelectOpenType == eSelectType.TestListRelease)
                    nFilterIdx = new int[2] { 1, 5 };

                if (nFilterIdx == null)
                    return;

                if (bFilterModeDoOff == true)
                    gridHistView.OptionsView.AllowCellMerge = false;
                else
                    gridHistView.OptionsView.AllowCellMerge = !gridHistView.OptionsView.AllowCellMerge;

                if (gridHistView.OptionsView.AllowCellMerge)
                {
                    simpleButtonFilter.Text = "Filter[ON](Ctrl+X)";

                    gridHistView.OptionsFilter.ColumnFilterPopupMode = ColumnFilterPopupMode.Excel;
                    for (int i = 0; i < gridHistView.Columns.Count; i++)
                    {
                        gridHistView.Columns[i].OptionsFilter.FilterPopupMode = FilterPopupMode.Excel;
                        gridHistView.Columns[i].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                    }

                    foreach (int nIdx in nFilterIdx)
                        gridHistView.Columns[nIdx].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.True;

                    /* FOR TEST
                    MergedRowsHelper helper = new MergedRowsHelper();
                    helper.Register(gridHistView);
                    */
                }
                else
                    simpleButtonFilter.Text = "Filter[OFF](Ctrl+X)";
            }
            catch
            {
                ;//
            }
            finally
            {
                gridHistView.EndUpdate();
            }
        }

        private void ExportTestList()
        {
            if (LoginStateCheck() == false) return;
            if (MainViewModeCheckErr()) return;
            if (SelectedRowCheckErr()) return;

            if (SelectOpenType != eSelectType.TestListFile) return;

            int nMaxStepVersion = Convert.ToInt32(gridHistView.GetFocusedRowCellValue("Step Version").ToString());

            string strNo = gridHistView.GetFocusedRowCellValue("No").ToString();
            string strName = gridHistView.GetFocusedRowCellValue("Name").ToString();
            string strTestType = gridHistView.GetFocusedRowCellValue("TestType").ToString();
            string strVersion = gridHistView.GetFocusedRowCellValue("FileVersion").ToString();
            string strProdCode = gridHistView.GetFocusedRowCellValue("ProdCode").ToString();
            string strFileName = gridHistView.GetFocusedRowCellValue("FileName").ToString();

            int nDataLoadPosition = 0;
            int nSelectVersion = nMaxStepVersion;

            if (nMaxStepVersion > 0)
            {
                SelectTestListForm SelectTLForm = new SelectTestListForm(eSelectType.TestListFile, ctrlDB, nMaxStepVersion);
                SelectTLForm.Location = Control.MousePosition;

                SelectTLForm.strNo = strNo;
                SelectTLForm.strName = strName;
                SelectTLForm.strTestType = strTestType;
                SelectTLForm.strVersion = strVersion;
                SelectTLForm.strProdCode = strProdCode;
                SelectTLForm.strFileName = strFileName;

                SelectTLForm.ShowDialog();

                if (SelectTLForm.DialogResult != DialogResult.OK)
                    return;

                nSelectVersion = Convert.ToInt32(SelectTLForm.nSelectedVersion);
                nDataLoadPosition = nMaxStepVersion - nSelectVersion;
            }

            //if (MessageBox.Show("Select [" + strNo + "/" + strName + "/" + strTestType + "/" + strVersion + "/" + strProdCode + "/" + strFileName + "] Test-List Version [" + nSelectVersion + "] a storage location. Would you like to create a test list file?", strSelectTable, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            if (MessageBox.Show("Select [" + strNo + "/" + strFileName + "/" + strTestType + "/" + strVersion + "/" + strProdCode + "] Test-List Version [" + nSelectVersion + "] a storage location. Would you like to create a test list file?", strSelectTable, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                byte[] ucTestListRawData = null;

                if (nDataLoadPosition > 0)
                {
                    string[] strTestListDataName = { "TestListData1", "TestListData2", "TestListData3", "TestListData4", "TestListData5", "TestListData6", "TestListData7", "TestListData8", "TestListData9", "TestListData10" };

                    string strAccessDataPos = strTestListDataName[nDataLoadPosition - 1];

                    string strQueryText = $"SELECT [TestListFileNo], [Name], [" + strAccessDataPos + $"] FROM [HIST_TestListFile] WHERE [TestListFileNo] = {strNo};"; // AND [Name] = '{strName}';";

                    DataTable dtQuery = ctrlDB.GetTable(strQueryText);

                    if (XCommons.isHasRow(dtQuery))
                    {
                        ucTestListRawData = new byte[((byte[])dtQuery.Rows[0][strAccessDataPos]).Length];
                        ((byte[])dtQuery.Rows[0][strAccessDataPos]).CopyTo(ucTestListRawData, 0);
                    }
                }
                else
                {
                    /*
                    string strQueryText = $"SELECT X.No, " +
                                       $"X.Name, " +
                                       $"X.TestType, " +
                                       $"X.Version, " +
                                       $"X.ProdCode, " +
                                       $"X.FileName, " +
                                       $"X.TestListData, " +
                                       $"FROM [dbo].[STOR_TestListFile] AS X " +
                                       $"WHERE " +
                                       $"Name = '" + SelectTestListFileInfo.Name + "' AND " +
                                       $"TestType = '" + SelectTestListFileInfo.TestType + "' AND " +
                                       $"Version = '" + SelectTestListFileInfo.Version + "' AND " +
                                       $"ProdCode = '" + SelectTestListFileInfo.ProdCode + "' AND " +
                                       $"FileName = '" + SelectTestListFileInfo.FileName + "';";
                    */

                    string strQueryText = $"SELECT X.No, " +
                                       $"X.Name, " +
                                       $"X.TestType, " +
                                       $"X.Version, " +
                                       $"X.ProdCode, " +
                                       $"X.FileName, " +
                                       $"X.TestListData " +
                                       $"FROM [dbo].[STOR_TestListFile] AS X " +
                                       $"WHERE " +
                                       $"No = " + strNo;

                    DataTable dtQuery = ctrlDB.GetTable(strQueryText);

                    if (XCommons.isHasRow(dtQuery) == false)
                        throw new Exception();

                    /*ucTestListRawData = new byte[((byte[])gridHistView.GetFocusedRowCellValue("TestListData")).Length];
                    ((byte[])gridHistView.GetFocusedRowCellValue("TestListData")).CopyTo(ucTestListRawData, 0);*/

                    ucTestListRawData = new byte[((byte[])dtQuery.Rows[0]["TestListData"]).Length];
                    ((byte[])dtQuery.Rows[0]["TestListData"]).CopyTo(ucTestListRawData, 0);
                }

                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string strsetPath = folderBrowserDialog.SelectedPath + @"\";

                    strsetPath += gridHistView.GetFocusedRowCellValue("FileName").ToString() + ".CpXv" +
                        gridHistView.GetFocusedRowCellValue("FileVersion").ToString() +
                        gridHistView.GetFocusedRowCellValue("ProdCode").ToString();

                    DialogResult dr = DialogResult.Yes;

                    if (File.Exists(strsetPath) == true)
                    {
                        dr = MessageBox.Show("It already exists under the same name. After checking the existing file, remove it or change the storage location. Replace an existing file?", strSelectTable, MessageBoxButtons.YesNo, MessageBoxIcon.Error);

                        if (dr == DialogResult.Yes)
                            File.Delete(strsetPath);
                    }

                    bool bDownloadResult = true;
                    if (dr == DialogResult.Yes)
                    {
                        try
                        {
                            byte[] ucgetTestListDecompressData = XDataArchive.DecompressGZipByteToByte(ucTestListRawData);
                            File.WriteAllBytes(strsetPath, (byte[])ucgetTestListDecompressData);
                        }
                        catch
                        {
                            bDownloadResult = false;

                            MessageBox.Show("Failed to download test-list.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        finally
                        {
                            if (bDownloadResult)
                                MessageBox.Show("Test-list download complete", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }

        private void SelectParentFullUpdate()
        {
            if (LoginStateCheck() == false) return;
            if (MainViewModeCheckErr()) return;
            if (SelectedRowCheckErr()) return;

            if (SelectOpenType != eSelectType.TestListVariant) return;

            try
            {
                ;// FindSameParentInformation();
            }
            catch (Exception e)
            {
                string strSelectInfo = "[" + SelectTestListVariantInfo.TestType + "][" + SelectTestListVariantInfo.FileName + "][" + SelectTestListVariantInfo.Version + "][" + SelectTestListVariantInfo.ProdCode + "]";
                MessageBox.Show(strSelectInfo + " No matching information was found for your selection.", strSelectInfo, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DoChangeSubView()
        {
            int iSetTestListNo = TestListNoCheckErr();

            if (iSetTestListNo < 0)
                return;

            eNowViewMode = eSetViewMode.SubView;

            simpleButtonViewVRFY.Text = "View STOR_TestListFile";
            simpleButtonViewVRFY.Appearance.BackColor = Color.Gainsboro;

            ViewRefresh("VRFY_TestListFileRelease", "TestListFileNo", iSetTestListNo.ToString());
        }

        private void DoChangeMainView(bool bReload = true)
        {
            eNowViewMode = eSetViewMode.MainView;

            simpleButtonViewVRFY.Text = "View VRFY TestList-File \r\n Release History";
            simpleButtonViewVRFY.Appearance.BackColor = Color.White;

            if (bReload)
                ViewRefresh(strSelectTable);
            else
                ViewChange();
        }

        private void ChangeViewType(eSetViewMode setViewMode, bool bAutoToggle = true)
        {
            if (bAutoToggle)
            {
                if (eNowViewMode == eSetViewMode.MainView)
                    DoChangeSubView();
                else
                    DoChangeMainView(false);
            }
            else
            {
                if (setViewMode == eSetViewMode.MainView)
                    DoChangeMainView();
                else
                    DoChangeSubView();
            }

            if (eNowViewMode == eSetViewMode.SubView)
                layoutControlItemSelVRFYVersion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            else
                layoutControlItemSelVRFYVersion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
        }

        private bool CopyReleaseListCheckDiffChildNo(int[] getSelectRows)
        {
            //string strChkChildNo = string.Empty;

            lstSetCopyRelease.Clear();

            strSetCopyProductNoData = string.Empty;

            bool bDiffrentInformation = false;

            string strProdNoP = string.Empty;
            string strTestType = string.Empty;
            string strVersion = string.Empty;
            string strProdCode = string.Empty;

            foreach (int n in getSelectRows)
            {
                DataRow dr = gridHistView.GetDataRow(n);

                //int nColSize = dr.ItemArray.Length;

                CReleaseInformation MakeInfo = new CReleaseInformation();

                MakeInfo.ProdNo_C = dr["C_ProdNo"].ToString();
                MakeInfo.TestCodeNo = Commons.ConvertTextToTryValue<int>(dr["TestCodeNo"].ToString(), -1);
                MakeInfo.TestCode = dr["TestCode"].ToString();
                MakeInfo.VariantNo = Commons.ConvertTextToTryValue<int>(dr["VariantNo"].ToString(), -1);
                MakeInfo.ProdNo_P = dr["P_ProdNo"].ToString();
                MakeInfo.TestType = dr["TestType"].ToString();
                MakeInfo.FileVersion = dr["FileVersion"].ToString();
                MakeInfo.ProdCode = dr["ProdCode"].ToString();
                MakeInfo.Config = dr["Config"].ToString();
                MakeInfo.RegDT = Convert.ToDateTime(dr["RegDT"].ToString());
                MakeInfo.RegUser = dr["RegUser"].ToString();
                MakeInfo.RegUserComment = dr["RegUserComment"].ToString();

                lstSetCopyRelease.Add(MakeInfo);

                if (strProdNoP == string.Empty)
                {
                    strProdNoP = MakeInfo.ProdNo_P;
                    strTestType = MakeInfo.TestType;
                    strVersion = MakeInfo.FileVersion;
                    strProdCode = MakeInfo.ProdCode;
                }
                else
                {
                    /*
                    if (strChkChildNo.CompareTo(dr["C_ProdNo"].ToString()) != 0)
                        throw new Exception("You can select and copy only the same release part number!");
                    */

                    if (strProdNoP.CompareTo(MakeInfo.ProdNo_P) != 0 ||
                        strTestType.CompareTo(MakeInfo.TestType) != 0 ||
                        strVersion.CompareTo(MakeInfo.FileVersion) != 0 ||
                        strProdCode.CompareTo(MakeInfo.ProdCode) != 0)
                    {
                        bDiffrentInformation = true;
                    }
                }
            }
            //
            if (bDiffrentInformation == false)
            {
                InputCopyReleaseNoForm InputProductNoForm = new InputCopyReleaseNoForm(ctrlDB);
                InputProductNoForm.Location = Control.MousePosition;

                InputProductNoForm.strProdNoP = strProdNoP;
                InputProductNoForm.strTestType = strTestType;
                InputProductNoForm.strVersion = strVersion;
                InputProductNoForm.strProdCode = strProdCode;

                InputProductNoForm.ShowDialog();

                if (InputProductNoForm.DialogResult == DialogResult.OK)
                    strSetCopyProductNoData = InputProductNoForm.strInputProductNo;
                else
                    bHasCopyData = false;
            }

            return true;
        }

        private void CopyData()
        {
            if (LoginStateCheck() == false) return;
            if (CheckSelectedData() == false) return;

            if (SelectOpenType == eSelectType.TestListFile) return;

            /*if (bCtrlKeyOn == false)
                return;*/

            try
            {
                bHasCopyData = true;

                int[] getSelectRows = gridHistView.GetSelectedRows();
                int nSelectedSize = gridHistView.SelectedRowsCount;

                if (SelectOpenType == eSelectType.TestListVariant)
                {
                    if (getSelectRows.Length != 1)
                        throw new Exception("At least one item must be selected!");
                }
                else if (SelectOpenType == eSelectType.TestListRelease)
                    CopyReleaseListCheckDiffChildNo(getSelectRows);
            }
            catch (Exception ex)
            {
                bHasCopyData = false;

                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void PasteData()
        {
            if (LoginStateCheck() == false) return;
            if (CheckSelectedData() == false) return;

            if (SelectOpenType == eSelectType.TestListFile) return;

            /*if (bCtrlKeyOn == false)
                return;*/

            if (bHasCopyData == false)
                return;

            DialogResult getResult = new DialogResult();
            getResult = DialogResult.None;

            if (SelectOpenType == eSelectType.TestListVariant)
            {
                TestListVariantCopyWizard CopyTestListVariant = new TestListVariantCopyWizard(ctrlDB,
                    TestListVariantCopyWizard.eSelectMode.Insert, SelectTestListVariantInfo);

                SetObjectPosition(CopyTestListVariant);

                EventClear(CopyTestListVariant);
                WizardCancelEvent += CopyTestListVariant.WizardCancelEvent;

                CopyTestListVariant.StartPosition = FormStartPosition.CenterParent;

                getResult = CopyTestListVariant.ShowDialog();

                if (getResult == DialogResult.OK)
                {
                    loadForm = new WaitProgressForm();
                    loadForm.setDescription("Proceeding ...");
                    loadForm.Location = new Point(this.Parent.Width / 2, this.Parent.Height / 2);
                    loadForm.Show();

                    Application.DoEvents();

                    foreach (CVariantInformation item in CopyTestListVariant.GetInsertList())
                    {
                        SetTestListVariantFieldInfo();

                        InsertProdTestListVariantInformation(item);

                        item.SelectVariantNo = GetProdTestListVariantNoFind(item);
                    }
                }
            }
            else if (SelectOpenType == eSelectType.TestListRelease)
            {
                TestListReleaseCopyWizard CopyTestListRelease = new TestListReleaseCopyWizard(ctrlDB,
                    TestListReleaseCopyWizard.eSelectMode.Insert, lstSetCopyRelease, strSetCopyProductNoData);

                SetObjectPosition(CopyTestListRelease);

                EventClear(CopyTestListRelease);
                WizardCancelEvent += CopyTestListRelease.WizardCancelEvent;

                CopyTestListRelease.StartPosition = FormStartPosition.CenterParent;

                getResult = CopyTestListRelease.ShowDialog();

                if (getResult == DialogResult.OK)
                {
                    loadForm = new WaitProgressForm();
                    loadForm.setDescription("Proceeding ...");
                    loadForm.Location = new Point(this.Parent.Width / 2, this.Parent.Height / 2);
                    loadForm.Show();

                    Application.DoEvents();

                    foreach (CReleaseInformation item in CopyTestListRelease.GetInsertList())
                        InsertReleaseListInformation(item);
                }
            }

            if (loadForm != null)
            {
                loadForm.Close();
                loadForm = null;
            }
            //
            if (getResult == DialogResult.OK)
            {
                //Unused TestListFile
                if (SelectOpenType == eSelectType.TestListVariant)
                {
                    ;//
                }
                else if (SelectOpenType == eSelectType.TestListRelease)
                {
                    ;//
                }
                else
                {
                    ;//
                }

                ViewRefresh();
            }

            bHasCopyData = false;
        }

        private void SetViewCustomTable(DataTable dt)
        {
            ViewgridControl.BeginInit();

            ViewgridControl.DataSource = null;

            gridHistView.RefreshData();

            ViewgridControl.DataSource = dt;

            ViewgridControl.Views[0].PopulateColumns();

            for (int i = 0; i < gridHistView.Columns.Count; i++)
                gridHistView.Columns[i].OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;

            ColumnStyleSet();

            gridHistView.BestFitColumns();

            ViewgridControl.EndInit();
        }


        private bool CheckRowSelectInfo()
        {
            object objHandle = null;

            bool bCheckResult = true;

            try
            {
                objHandle = gridHistView.GetFocusedRowCellValue("No");
            }
            catch
            {
                objHandle = null;

                bCheckResult = false;
            }
            finally
            {
                ;//
            }

            return bCheckResult;
        }

        private void GoToTestListFile()
        {
            if (LoginStateCheck() == false) return;

            if (SelectOpenType != eSelectType.TestListVariant)
            {
                MessageBox.Show("Change the view state to the Main View, It could be a Prod Variant table.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }

            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
                return;

            int nVariantUniqueNo = Convert.ToInt32(AbsoluteUniqueNo);

            string strQueryText = $"SELECT X.No AS 'TestListFileNo' FROM [STOR_TestListFile] AS X INNER JOIN [PROD_Variant] AS Z ON Z.No = {nVariantUniqueNo} WHERE X.No = Z.TestListFileNo;";

            DataTable dtQuery = ctrlDB.GetTable(strQueryText);

            if (XCommons.isHasRow(dtQuery))
            {
                int nTestListFileNo = Convert.ToInt32(dtQuery.Rows[0]["TestListFileNo"].ToString());

                ctrlChild.GoToFindTestListFileFocus(nTestListFileNo);

            }
        }

        private void GoToVariant(int nSelectVariantNo = int.MaxValue)
        {
            if (LoginStateCheck() == false) return;

            if (SelectOpenType != eSelectType.TestListRelease)
            {
                MessageBox.Show("Change the view state to the Main View, It could be a Prod Release table.", strSelectTable, MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;
            }

            if (AbsoluteIndexRow < 0 || AbsoluteUniqueNo.Length < 0)
                return;

            int nReleaseUniqueNo = Convert.ToInt32(AbsoluteUniqueNo);

            string strQueryText = $"SELECT X.No AS 'VariantNo' FROM [PROD_Variant] AS X INNER JOIN [PROD_Release] AS Z ON Z.No = {nReleaseUniqueNo} WHERE X.No = Z.VariantNo;";

            DataTable dtQuery = ctrlDB.GetTable(strQueryText);

            if (XCommons.isHasRow(dtQuery))
            {
                int nTestListVariantNo = Convert.ToInt32(dtQuery.Rows[0]["VariantNo"].ToString());

                ctrlChild.GoToFindVariantFocus(nTestListVariantNo);
            }
        }
    }
}