using DevExpress.Data.Helpers;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Navigation;

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;
using SystemX.Common.Serialization;
using SystemX.Common.Archive;
using System.Threading.Tasks;

using SystemX.Common.Protocol.SIA;

using SystemX.Net.Middleware.Commons;

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

namespace SystemX.Net.MiddlewareUI
{
    public partial class MainForm : DevExpress.XtraBars.FluentDesignSystem.FluentDesignForm
    {
        private bool IsImageExtension(string strFileNameInfo, bool bOnlyExtension = true)
        {
            if (bOnlyExtension)
                return -1 != Array.IndexOf(COMMON.mediaExtensions, strFileNameInfo.ToUpperInvariant());
            else
                return -1 != Array.IndexOf(COMMON.mediaExtensions, Path.GetExtension(strFileNameInfo).ToUpperInvariant());
        }
 
        public List<byte[]> QueryStreamProcess(string strGetQuery, out byte[] ucQueryByteArray, out DataSet setResultDataSet, params string[] strSendParameters)
        {
            SqlDataReader xSqlReader = null;

            int iFieldCnt = 0;
            int iRecordsAffectedCnt = 0;
            bool bHasRow = false;

            ucQueryByteArray = null;

            setResultDataSet = null;

            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            DataSet getDS = Task.Run(() =>
            {
                try
                {
                    try
                    {
                        xSqlReader = MngDBConn.CurrentConnection(eConnCategory.Main).QueryDatabase(strGetQuery);

                        if (xSqlReader != null)
                        {
                            iFieldCnt = xSqlReader.FieldCount;
                            iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                            bHasRow = xSqlReader.HasRows;

                            dt.Load(xSqlReader);
                            ds.Tables.Add(dt);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                    }
                }
                finally
                {
                    if (xSqlReader != null)
                        xSqlReader.Close();

                    xSqlReader = null;
                }

                return ds;
            }).Result;

            if(XCommons.isHasRow(ds))
                setResultDataSet = ds.Copy();

            List<byte[]> getStreamList = XCommons.ObjectToByteStreamList(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.RAW_SIZE), getDS, null, 0, strSendParameters);

            return getStreamList;
        }

        public void QueryResultRemake(DataSet dsResult, int iSetFieldCnt, int iSetRecordsAffectedCnt, bool bSetHasRow, out byte[] ucQueryByteArray, params string[] strParameters)
        {
            int iFieldCnt = iSetFieldCnt;
            int iRecordsAffectedCnt = iSetRecordsAffectedCnt;
            bool bHasRow = bSetHasRow;

            ucQueryByteArray = null;

            ucQueryByteArray = XCommons.ObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER),
                dsResult,
                null,
                0,
                iRecordsAffectedCnt,
                bHasRow,
                iFieldCnt,
                strParameters);
        }

        public Tuple<DataSet, int, int, bool> QueryProcess(string strGetQuery, out byte[] ucQueryByteArray, params string[] strParameters)
        {
            SqlDataReader xSqlReader = null;

            int iFieldCnt = 0;
            int iRecordsAffectedCnt = 0;
            bool bHasRow = false;

            ucQueryByteArray = null;

            DataSet getDS = Task.Run(() =>
            {
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();

                bool bLockProcess = false;
                if (strGetQuery.IndexOf("HIST_TestResult") >= 0)
                    bLockProcess = true;

                if(bLockProcess)
                {
                    //lock (objSingleTransactionDataAccessWait)
                    {
                        try
                        {
                            try
                            {
                                xSqlReader = MngDBConn.CurrentConnection(eConnCategory.Main).QueryDatabase(strGetQuery);

                                if (xSqlReader != null)
                                {
                                    iFieldCnt = xSqlReader.FieldCount;
                                    iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                                    bHasRow = xSqlReader.HasRows;

                                    dt.Load(xSqlReader);
                                    ds.Tables.Add(dt);
                                }
                            }
                            catch (Exception e)
                            {
                                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                            }
                        }
                        finally
                        {
                            if (xSqlReader != null)
                                xSqlReader.Close();

                            xSqlReader = null;
                        }
                    }
                }
                else
                {
                    try
                    {
                        try
                        {
                            xSqlReader = MngDBConn.CurrentConnection(eConnCategory.Main).QueryDatabase(strGetQuery);

                            if (xSqlReader != null)
                            {
                                iFieldCnt = xSqlReader.FieldCount;
                                iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                                bHasRow = xSqlReader.HasRows;

                                dt.Load(xSqlReader);
                                ds.Tables.Add(dt);
                            }
                        }
                        catch (Exception e)
                        {
                            MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                        }
                    }
                    finally
                    {
                        if (xSqlReader != null)
                            xSqlReader.Close();

                        xSqlReader = null;
                    }
                }
               
                return ds;
            }).Result;

            ucQueryByteArray = XCommons.ObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.DATASET_TRANSEFER), 
                getDS, 
                null, 
                0, 
                iRecordsAffectedCnt, 
                bHasRow, 
                iFieldCnt,
                strParameters);

            return new Tuple<DataSet, int, int, bool>(getDS, iRecordsAffectedCnt, iFieldCnt, bHasRow);
        }

        private bool ExcuteNonQueryCommandProcess(SqlCommand cmd)
        {
            return Task.Run(() =>
            {
                bool bExcuteResult = true;

                try
                {
                    try
                    {
                        bExcuteResult = MngDBConn.CurrentConnection(eConnCategory.Main).ExecuteNonCommandQuery(cmd);
                    }
                    catch (Exception e)
                    {
                        bExcuteResult = false;

                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + cmd.CommandText + "> Query excute fail![SystemX.Net.MiddlewareUI : MainForm.AsyncExcuteNonQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                    }
                }
                finally
                {
                    ;
                }

                return bExcuteResult;
            }).Result;
        }

        private bool ExcuteNonQueryStreamProcess(eConnCategory eConnType, SqlCommand cmd)
        {
            return Task.Run(() =>
            {
                bool bExcuteResult = true;

                try
                {
                    try
                    {
                        bExcuteResult = MngDBConn.CurrentConnection(eConnType).ExecuteNonStreamQuery(cmd);
                    }
                    catch (Exception e)
                    {
                        bExcuteResult = false;

                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + cmd.CommandText + "> Query excute fail![SystemX.Net.MiddlewareUI : MainForm.AsyncExcuteNonQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                    }
                }
                finally
                {
                    ;
                }

                return bExcuteResult;
            }).Result;
        }

        private DataSet QueryCommandProcess(eConnCategory eConnType, string strGetQuery, bool bUseTransaction = false)
        {
            return Task.Run(() =>
            {
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();

                try
                {
                    SqlDataReader xSqlReader = null;

                    try
                    {
                        int iFieldCnt = 0;
                        int iRecordsAffectedCnt = 0;
                        bool bHasRow = false;

                        try
                        {
                            xSqlReader = MngDBConn.CurrentConnection(eConnType).QueryCommandDatabase(strGetQuery, bUseTransaction);

                            if (xSqlReader != null)
                            {
                                iFieldCnt = xSqlReader.FieldCount;
                                iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                                bHasRow = xSqlReader.HasRows;

                                dt.Load(xSqlReader);
                                ds.Tables.Add(dt);
                            }
                        }
                        catch (Exception e)
                        {
                            MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.AsyncQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                        }
                    }
                    finally
                    {
                        if (xSqlReader != null)
                            xSqlReader.Close();

                        xSqlReader = null;
                    }
                }
                finally
                {
                    ;
                }

                return ds;
            }).Result;
        }

        private DataSet QueryStreamProcess(eConnCategory eConnType, string strGetQuery)
        {
            return Task.Run(() =>
            {
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();

                try
                {
                    SqlDataReader xSqlReader = null;

                    try
                    {
                        int iFieldCnt = 0;
                        int iRecordsAffectedCnt = 0;
                        bool bHasRow = false;

                        try
                        {
                            xSqlReader = MngDBConn.CurrentConnection(eConnType).QueryStreamDatabase(strGetQuery);

                            if (xSqlReader != null)
                            {
                                iFieldCnt = xSqlReader.FieldCount;
                                iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                                bHasRow = xSqlReader.HasRows;

                                dt.Load(xSqlReader);
                                ds.Tables.Add(dt);
                            }
                        }
                        catch (Exception e)
                        {
                            MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.AsyncQueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                        }
                    }
                    finally
                    {
                        if (xSqlReader != null)
                            xSqlReader.Close();

                        xSqlReader = null;
                    }
                }
                finally
                {
                    ;
                }

                return ds;
            }).Result;
        }

        private DataSet QueryProcess(string strGetQuery)
        {
            return Task.Run(() =>
            {
                SqlDataReader xSqlReader = null;

                DataSet ds = new DataSet();
                DataTable dt = new DataTable();

                int iFieldCnt = 0;
                int iRecordsAffectedCnt = 0;
                bool bHasRow = false;

                try
                {
                    try
                    {
                        xSqlReader = MngDBConn.CurrentConnection(eConnCategory.Main).QueryDatabaseSub(strGetQuery);

                        if (xSqlReader != null)
                        {
                            iFieldCnt = xSqlReader.FieldCount;
                            iRecordsAffectedCnt = xSqlReader.RecordsAffected;
                            bHasRow = xSqlReader.HasRows;

                            dt.Load(xSqlReader);
                            ds.Tables.Add(dt);
                        }
                    }
                    catch (Exception e)
                    {
                        MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") + @"<" + strGetQuery + "> Query process fail![SystemX.Net.MiddlewareUI : MainForm.QueryProcess]\r\n" + e.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                    }
                }
                finally
                {
                    if (xSqlReader != null)
                        xSqlReader.Close();

                    xSqlReader = null;
                }

                return ds;
            }).Result;
        }
    }
}
