using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
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.Comm;
using SystemX.Net.Comm.IIS_FTP;
using SystemX.Net.Schedule;
using SystemX.Net.XAdaptor.PC;
using static SystemX.Net.Platform.Common.Util.LogMessage;

namespace SystemX.Net.XAdaptor.Manager
{
    public class XAdaptorManager
    {
    	private string strCreateConfigFilePos;

        public XAdaptorManager(string strConfigFilePos = "")
        {
            MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                    @"Use CP-Server[X] Adaptor Version for [CPXV2][v240529] " +
                    "[SystemX.Net.XAdaptor.Manager : XAdaptorManager]", ConsoleColor.Green, LogMessageLevel.FATAL);

			strCreateConfigFilePos = string.Empty;

            Create();

            strCreateConfigFilePos = strConfigFilePos;

            if(strCreateConfigFilePos.Length > 0)
                SetConfigureFilePos(strCreateConfigFilePos);   
      	}

        public void Create()
        {
            xAdaptor = new XAdaptorPC();

            if (strCreateConfigFilePos.Length > 0)
                SetConfigureFilePos(strCreateConfigFilePos);
        }

        private XAdaptorPC xAdaptor;

        public IXPCAdaptor MgrConn
        {
            get
            {
                return xAdaptor;
            }
        }

        public IUIM MgrUIMConn
        {
            get
            {
                return xAdaptor;
            }
        }

        public IComXPCAdaptor MgrComConn
        {
            get
            {
                return xAdaptor;
            }
        }

        public XAdaptorSystem GetAdaptorHandler
        {
            get
            {
                return xAdaptor;
            }
        }

        public bool GetClientInfoState()
        {
            return xAdaptor.StateClientGetInformation;
        }

        public long GetLastCommandTime()
        {
            return xAdaptor.GetLastCommandTime();
        }

        public long GetLastStreamTime()
        {
            return xAdaptor.GetLastStreamTime();
        }

        public bool IsConnect { get { return xAdaptor.StateClientSocketConnect && xAdaptor.StateClientStreamSocketConnect; } }

        public bool CommandSocketConn { get { return xAdaptor.StateClientSocketConnect; } }

        public bool StreamSocketConn { get { return xAdaptor.StateClientStreamSocketConnect; } }

        public bool GetServerTestListLoadState()
        {
            return GetAdaptorHandler.ServerTestListLoadState;
        }

        public bool CheckStationTestListReload(int nStationID)
        {
            bool bNeedReload = false;

            foreach(int nStID in xAdaptor.GetReloadNeedStation())
            {
                if (nStID == nStationID)
                {
                    if (xAdaptor.GetStateReloadNeedTestList(nStID))
                        bNeedReload = true;

                    break;
                }
            }

            return bNeedReload;
        }

        private int[] NeedTestListReloadList()
        {
            return xAdaptor.GetReloadNeedStation();
        }
        private bool GetStationTestListReload(int nStationID)
        {
            return xAdaptor.GetStateReloadNeedTestList(nStationID);
        }
        public void SetStationTestListReloadStateOff(int nStationID)
        {
            xAdaptor.SetStateReloadNeedTestList(nStationID);
        }

        public IControlTestListDataSet GetTestListContainer()
        {
            return xAdaptor.CurrentTestList();
        }

        public DataSet GetTestListDataSet()
        {
            return xAdaptor.CurrentTestList().getTestListDataSet();
        }

        public eSetConfigFileResult SetConfigureFilePos(string strConfigFilePos = "")
        {
            return xAdaptor.SetConfigureFile(strConfigFilePos);
        }

        /*
        public bool CheckServerState()
        {
            return ((IXPCAdaptor)xAdaptor).WaitCheckServerState();
        }
        */

		public async Task<bool> AsyncWaitCheckServerState(bool bRetryAutoConnect = true)
        {      
            bool bResult = await ((IXPCAdaptor)xAdaptor).RestoreConnAfterConfirmConn(bRetryAutoConnect).ConfigureAwait(false);

            if (bResult)
            {
                GetAdaptorHandler.ServerTestListLoadState = false;
            }

            return bResult;
        }

        public eFTPServiceStatus CheckStateFTP()
        {
            return GetAdaptorHandler.StateFTP;
        }

        private eFTPServiceStatus StartFTP()
        {
            GetAdaptorHandler.StateFTP = xAdaptor.StartFTPService();

            return GetAdaptorHandler.StateFTP;
        }
        
        public async Task<bool> Connect(string strConfigFilePos = "")
        {
            if (xAdaptor.SetConfigureFile(strConfigFilePos) == eSetConfigFileResult.SetConfigFail)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                    @"Config File Error. [SystemX.Net.XAdaptor.Manager : XAdaptorManager : Connect]\r\n",
                    ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                return false;
            }

            // TODO : FTP ALIS
            StartFTP();

            xAdaptor.ConnectStartStyleAuto = true;
			
            bool bGetResult = true;
            for (int i = 0; i < 3; i++)
            {
                bGetResult = await xAdaptor.ComClientTryDistributionConnet();

                //return xAdaptor.ComClientTryConnet();

                if (bGetResult)
                    break;
            }

            return bGetResult;
        }
		
        public async Task<bool> WaitConnect(string strConfigFilePos = "")
        {
            if (xAdaptor.SetConfigureFile(strConfigFilePos) == eSetConfigFileResult.SetConfigFail)
            {
                MessageOutput.ConsoleWrite(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss>>") +
                    @"Config File Error. [SystemX.Net.XAdaptor.Manager : XAdaptorManager : Connect]\r\n",
                    ConsoleColor.Yellow, LogMessageLevel.DEBUG);

                return false;
            }

            // TODO : FTP ALIS
            StartFTP();

            xAdaptor.ConnectStartStyleAuto = false;

            bool bGetResult = true;
            for (int i = 0; i < 3; i++)
            {
                bGetResult = await xAdaptor.WaitComClientTryDistributionConnet();

                if (bGetResult)
                    break;
            }

            return bGetResult;
        }

        public bool Disconnect()
        {
            return xAdaptor.ComClientTryDisconnect();
        }
    }
}

