using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using SystemX.Common;
using SystemX.Common.Serialization;
using SystemX.Net.BaseProtocol;
using SystemX.Net.Schedule;
using SystemX.Net.XAdaptor;
using static SystemX.Net.Platform.Common.Util.LogMessage;

namespace SystemX.Net.XAdaptor.PC
{
    public partial class XAdaptorPC
    {
        private byte SendCallQuery(string strQueryCallID, params string[] strParameterValues)
        {
            QUERY_PACKET QueryPacket = new QUERY_PACKET();
            int iSizeQueryPacket = Marshal.SizeOf(QueryPacket);
            byte[] ucQueryPacketArray = new byte[iSizeQueryPacket];

            QueryPacket = (QUERY_PACKET)SystemXNetSerialization.RawDeSerialize(ucQueryPacketArray, QueryPacket.GetType());

            string strSendText = string.Empty;
            strSendText = "UserQueryCall;";

            if (strParameterValues.Length > 0)
            {
                strSendText += (strQueryCallID + ";");

                foreach (string strParam in strParameterValues)
                {
                    strSendText += (strParam + ";");
                }

                strSendText = strSendText.Remove(strSendText.Length - 1, 1);
            }
            else
                strSendText += strQueryCallID;

            QueryPacket.objQueryText[0].Data = strSendText;

            ucQueryPacketArray = XCommons.SpecialObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.USER_QUERY), QueryPacket);

            return FlowCommandControl.InsertSendQueue(DateTime.Now, ucQueryPacketArray, null, true);
        }

        private DataSet WaitCallQueryLookUp(string strQueryCallID, params string[] strParameterValues)
        {
            if (thisConnInfo.ConnectCommandState == false)
                return null;
            if (thisConnInfo.InitialInfoState == false)
                return null;

            DataSet dsReturnSet = null;

            try
            {
                thisConnInfo.OnCommandTime();

                try
                {
                    byte ucGetLabel = SendCallQuery(strQueryCallID, strParameterValues);

                    WaitThreadJoin(waitCommandParam, FlowCommandControl, ucGetLabel);

                    if (QueryResult.QueryDataSet != null)
                    {
                        if (QueryResult.bQueryResult)       //Query 문 실행 성공
                            dsReturnSet = QueryResult.QueryDataSet;
                        else                                //Query 문 실행 실패(구문 오류 또는 연결 오류)
                            dsReturnSet = null;
                    }
                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                      @"Registered query call error. [" + strQueryCallID + "][SystemX.Net.XAdaptor.PC - IXPCAdaptor : XPCAdaptor.WaitCallQuery]\r\n" +
                      ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
                finally
                {
                    ;//
                }
            }
            finally
            {
                ;
            }

            return dsReturnSet;
        }

        private DataSet WaitCallQuery(string strQueryCallID, params string[] strParameterValues)
        {
            if (thisConnInfo.ConnectCommandState == false)
                return null;
            if (thisConnInfo.InitialInfoState == false)
                return null;
            if (LoadInfo.SIMPLE_LOOKUP_OPTION == true)
                return null;

            DataSet dsReturnSet = null;

            try
            {
                thisConnInfo.OnCommandTime();

                try
                {
                    byte ucGetLabel = SendCallQuery(strQueryCallID, strParameterValues);

                    WaitThreadJoin(waitCommandParam, FlowCommandControl, ucGetLabel);

                    if (QueryResult.QueryDataSet != null)
                    {
                        if (QueryResult.bQueryResult)       //Query 문 실행 성공
                            dsReturnSet = QueryResult.QueryDataSet;
                        else                                //Query 문 실행 실패(구문 오류 또는 연결 오류)
                            dsReturnSet = null;
                    }
                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                      @"Registered query call error. [" + strQueryCallID + "][SystemX.Net.XAdaptor.PC - IXPCAdaptor : XPCAdaptor.WaitCallQuery]\r\n" +
                      ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
                finally
                {
                    ;//
                }
            }
            finally
            {
                ;
            }

            return dsReturnSet;
        }

        public DataSet WaitUserQuery(string strQuery)
        {
            if (thisConnInfo.ConnectCommandState == false)
                return null;
            if (thisConnInfo.InitialInfoState == false)
                return null;
            if (LoadInfo.SIMPLE_LOOKUP_OPTION == true)
                return null;

            string[] strCheck = strQuery.Split(' ');
            string strUpperText = string.Empty;

            foreach (string strItem in strCheck)
            {
                strUpperText = strItem.ToUpper();

                if (strUpperText.CompareTo("INSERT") == 0 ||
                strUpperText.CompareTo("UPDATE") == 0 ||
                strUpperText.CompareTo("DELETE") == 0)
                {
                    MessageBox.Show("SQL control syntax other than SELECT syntax is not supported.", "XAdaptor", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return null;
                }
            }

            string strQueryText = strQuery.ToUpper();

            DataSet dsReturnSet = null;

            try
            {
                thisConnInfo.OnCommandTime();

                try
                {
                    QUERY_PACKET QueryPacket = new QUERY_PACKET();
                    int iSizeQueryPacket = Marshal.SizeOf(QueryPacket);
                    byte[] ucQueryPacketArray = new byte[iSizeQueryPacket];
                    QueryPacket = (QUERY_PACKET)SystemXNetSerialization.RawDeSerialize(ucQueryPacketArray, QueryPacket.GetType());
                    QueryPacket.objQueryText[0].Data = strQuery;
                    ucQueryPacketArray = XCommons.SpecialObjectToByteStream(new BASE_PROTOCOL(BASE_PROTOCOL.PROTOCOL_CODE.SYSTEM_QUERY), QueryPacket);

                    byte ucGetLabel = FlowCommandControl.InsertSendQueue(DateTime.Now, ucQueryPacketArray, null, true);
                    
                    WaitThreadJoin(waitCommandParam, FlowCommandControl, ucGetLabel);

                    if (QueryResult.QueryDataSet != null)
                    {
                        if (QueryResult.bQueryResult)       //Query 문 실행 성공
                            dsReturnSet = QueryResult.QueryDataSet;
                        else                                //Query 문 실행 실패(구문 오류 또는 연결 오류)
                            dsReturnSet = null;
                    }
                }
                catch (Exception ex)
                {
                    MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                      @"User program query call error. [" + strQuery + "][SystemX.Net.XAdaptor.PC - IXPCAdaptor : XPCAdaptor.WaitUserQuery]\r\n" +
                      ex.Message, ConsoleColor.Yellow, LogMessageLevel.DEBUG);
                }
                finally
                {
                }
            }
            finally
            {
                ;
            }

            return dsReturnSet;
        }
    }
}
