using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;
using System.Diagnostics;

using SystemX.Net;
using SystemX.Common;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Comm;
using SystemX.Net.Schedule;
using SystemX.Net.DB.LogProcess;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;

//using SystemX.Common.Protocol.SIA;

using static SystemX.Net.Platform.Common.Util.LogMessage;
using System.Threading;
using SystemX.Net.Platform.Common.ExtensionMethods;

using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;
using static SystemX.Net.DB.LogProcess.XLogDBConnManager;
using System.Net.NetworkInformation;

namespace SystemX.Net.MiddlewareUI
{
    public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
    {
        public bool CPX_ReadVRFYList(int nConnId, int nTestListNo, string strProcessDebugInfo, out int nReadStepVersion, /*int nSetReadStepVersion,*/ int nLoadPosition = 0, bool bForceRead = true)
        {
            nReadStepVersion = int.MaxValue;

            try
            {
                string strGetVersionTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VERSION_TABLE;
                string strGetVRFYTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VRFY_TABLE;

                try
                {
                    //해당 테스트리스 정보 마지막 업데이트 번호 가져오기
                    thisConnInfo[nConnId].getLatestStepVer = QueryStreamProcess(eConnCategory.Main, "SELECT LatestStepVersion FROM [" + strGetVersionTableName + "] WHERE TestlistNo = " + nTestListNo + ";");

                    nReadStepVersion = Convert.ToInt32(thisConnInfo[nConnId].getLatestStepVer.Tables[0].Rows[0]["LatestStepVersion"]);
                }
                catch
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
                       @" CpLogProcess [" + strGetVersionTableName + "] MSV failed to obtain the most recent update number for VRFY (VRFY could not be found with the loading test list information.). [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);

                    throw new Exception();
                }

                //이전 버전 사용 일시
                if (nLoadPosition > 0)
                    nReadStepVersion -= nLoadPosition;

                /* Changed
                 * 마지막 업데이트 번호가 다를때만 테스트리스트(VRFY) 갱신(Enabled Step 별 가장 최근 업데이트 번호 목록 정리)
                 * > 항상 최근 해당 테스트리스트(VRFY) 조회로 변경 
                 * > 매번 조회시 속도 문제로 동일한 VRFY일 경우 SKIP
                 * > INDEX 사용
                */
                if (bForceRead || 
                    (thisConnInfo[nConnId].bQueryVRFYLoaded == false ||
                    thisConnInfo[nConnId].nLastQueryTLFileNumber != nTestListNo ||
                    thisConnInfo[nConnId].nLastQueryTLStepVersion != nReadStepVersion))
                {
                    try
                    {
                        thisConnInfo[nConnId].dsLatestVRFYRel = QueryStreamProcess(eConnCategory.Main, "SELECT * FROM ( " +
                            "SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
                            "AS RN FROM [" + strGetVRFYTableName + "] WITH (INDEX=[CSK_VRFY_Release_1]) WHERE TestlistNo = " + nTestListNo + " " +
                            "AND StepVersion <= " + nReadStepVersion + ") X WHERE RN = 1 ORDER BY X.StepID ASC;");

                        thisConnInfo[nConnId].dsLongTermLatestVRFYRel = thisConnInfo[nConnId].dsLatestVRFYRel.Copy();

                        DataColumn[] keys1 = new DataColumn[1];
                        keys1[0] = new DataColumn();
                        keys1[0] = thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].Columns["StepID"];

                        thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].PrimaryKey = keys1;

                        DataColumn[] keys2 = new DataColumn[1];
                        keys2[0] = new DataColumn();
                        keys2[0] = thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].Columns["StepID"];

                        thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].PrimaryKey = keys2;

                        thisConnInfo[nConnId].nLastQueryTLFileNumber = nTestListNo;
                        thisConnInfo[nConnId].nLastQueryTLStepVersion = nReadStepVersion;

                        thisConnInfo[nConnId].bQueryVRFYLoaded = true;
                    }
                    catch
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
                           @" CpLogProcess Failed to get list from [" + strGetVRFYTableName + "]. [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);

                        throw new Exception();
                    }
                }
            }
            catch
            {
                return false;
            }

            return true;
        }

        public bool CPXV2_ReadVRFYList(int nConnId, int nTestListFileNo, int nTestListVariantNo, string strProcessDebugInfo, out int nReadStepVersion, /*int nSetReadStepVersion,*/ int nLoadPosition = 0, bool bForceRead = true)
        {
            nReadStepVersion = int.MaxValue;

            try
            {
                //HIST_TestListFileLatestStepVersion
                //VRFY_TestListFileRelease

                string strGetVersionTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VERSION_TABLE;
                string strGetVRFYTableName = MngDBLogConn.GetDBConnectInfo().ConnMain.VRFY_TABLE;

                try
                {
                    //해당 테스트리스 정보 마지막 업데이트 번호 가져오기
                    thisConnInfo[nConnId].getLatestStepVer = QueryStreamProcess(eConnCategory.Main, "SELECT LatestStepVersion FROM [" + strGetVersionTableName + "] WITH(NOLOCK) WHERE TestListFileNo = " + nTestListFileNo + ";");

                    nReadStepVersion = Convert.ToInt32(thisConnInfo[nConnId].getLatestStepVer.Tables[0].Rows[0]["LatestStepVersion"]);
                }
                catch
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
                       @" CpLogProcess [" + strGetVersionTableName + "] MSV failed to obtain the most recent update number for VRFY (VRFY could not be found with the loading test list information.). [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);

                    throw new Exception();
                }

                //이전 버전 사용 일시
                if (nLoadPosition > 0)
                    nReadStepVersion -= nLoadPosition;

                /* Changed
                 * 마지막 업데이트 번호가 다를때만 테스트리스트(VRFY) 갱신(Enabled Step 별 가장 최근 업데이트 번호 목록 정리)
                 * > 항상 최근 해당 테스트리스트(VRFY) 조회로 변경 
                 * > 매번 조회시 속도 문제로 동일한 VRFY일 경우 SKIP
                 * > INDEX 사용
                */
                if (bForceRead || 
                    (thisConnInfo[nConnId].bQueryVRFYLoaded == false ||
                    thisConnInfo[nConnId].nLastQueryTLFileNumber != nTestListFileNo ||
                    thisConnInfo[nConnId].nLastQueryTLVariantNumber != nTestListVariantNo ||
                    thisConnInfo[nConnId].nLastQueryTLStepVersion != nReadStepVersion))
                {
                    try
                    {
                        string strQueryVRFY = "SELECT * FROM ( " +
                            "SELECT *, ROW_NUMBER() OVER(PARTITION BY StepID ORDER BY StepVersion DESC) " +
                            "AS RN FROM [" + strGetVRFYTableName + "] WITH (NOLOCK, INDEX=[CSK_VRFY_Release_2]) WHERE TestListFileNo = " + nTestListFileNo + " " +
                            "AND StepVersion <= " + nReadStepVersion + ") X WHERE RN = 1 ORDER BY X.StepID ASC;";

                        thisConnInfo[nConnId].dsLatestVRFYRel = QueryStreamProcess(eConnCategory.Main, strQueryVRFY);

                        thisConnInfo[nConnId].dsLongTermLatestVRFYRel = thisConnInfo[nConnId].dsLatestVRFYRel.Copy();

                        DataColumn[] keys1 = new DataColumn[1];
                        keys1[0] = new DataColumn();
                        keys1[0] = thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].Columns["StepID"];

                        thisConnInfo[nConnId].dsLatestVRFYRel.Tables[0].PrimaryKey = keys1;

                        DataColumn[] keys2 = new DataColumn[1];
                        keys2[0] = new DataColumn();
                        keys2[0] = thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].Columns["StepID"];

                        thisConnInfo[nConnId].dsLongTermLatestVRFYRel.Tables[0].PrimaryKey = keys2;

                        thisConnInfo[nConnId].nLastQueryTLFileNumber = nTestListFileNo;
                        thisConnInfo[nConnId].nLastQueryTLVariantNumber = nTestListVariantNo;
                        thisConnInfo[nConnId].nLastQueryTLStepVersion = nReadStepVersion;

                        thisConnInfo[nConnId].bQueryVRFYLoaded = true;
                    }
                    catch
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + strProcessDebugInfo +
                           @" CpLogProcess Failed to get list from [" + strGetVRFYTableName + "]. [SystemX.Net.MiddlewareUI : MainForm.ReadVRFYList]", ConsoleColor.Red, LogMessageLevel.FATAL);

                        throw new Exception();
                    }
                }
            }
            catch
            {
                return false;
            }

            return true;
        }
    }
}
