﻿using System;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;
using System.Timers;
using IndianHealthService.BMXNet.Net;
using IndianHealthService.BMXNet.Services;
using IndianHealthService.BMXNet.Model;
using System.Windows.Forms;
 
namespace IndianHealthService.BMXNet
{
    /// <summary>
    /// BMXNetBroker implements low-level socket connectivity to RPMS databases.
    /// The VA RPC Broker must be running on the RPMS server in order for 
    /// BMXNetBroker to connect.
    /// </summary>
    [DnsPermission(SecurityAction.Assert, Unrestricted = true)]
    internal abstract class BMXNetBroker:EncryptionProvider
    {
        public static BMXNetBroker CreateSocketBroker()
        {
            return (BMXNetBroker)new BMXNetSocketBroker();
        }

        private Log _log = new NullLog();

        public Log Log
        {
            get { return _log; }
            set { _log = value; }
        }


        public BMXNetBroker()
        {
            this.EncryptionProvider = new BMXAdeCrypto();       
        }

        internal RemoteSessionPool CreateRemoteSessionPool(BMXNetSessionConnectionSource aSource, int maxConnectionCount)
        {
            BMXRemoteSessionPool pool = new BMXRemoteSessionPool();
            pool.Log = this.Log;
            pool.MaxSessions = maxConnectionCount;
            pool.Begin(aSource);
            return pool;
        }
      
        public abstract bool IsConnected { get; }

        public abstract RemoteSession PrimaryRemoteSession { get; }


        public virtual bool Open(string aServer, int aPort, string aNameSpace, string anAccessCode, string aVerifyCode, int sendTimeout, int receiveTimeout)
        {
            throw new NotSupportedException();
        }

        public virtual bool Open(string aServer, int aPort, string aNameSpace, WindowsIdentity windowsIdentity, int sendTimeout, int receiveTimeout)
        {
            throw new NotSupportedException();
        }

        private EncryptionProvider _encryptionProvider = null;

        public EncryptionProvider EncryptionProvider
        {
            get
            {
                return _encryptionProvider;
            }
            set
            {
                _encryptionProvider = value;
            }
        }


        public String Duz
        {
            get { return this.User.Duz; }
        }

        private User _user=null;

        public User User
        {
            get { return _user; }
            set { _user = value; }
        }

    
        public double ImHereServer()
        {
            try
            {
                DateTime past = DateTime.Now;
                this.PrimaryRemoteSession.TransmitRPC("BMX IM HERE", "");
                return (DateTime.Now - past).TotalMilliseconds;
            }
            catch
            {
                return -1;
            }
        }


        public abstract void Close();
   
        public abstract RemoteSessionPool RemoteSessionPool { get; }
 
        
        #region Piece Functions

        /// <summary>
        /// Corresponds to M's $L(STRING,DELIMITER)
        /// </summary>
        /// <param name="sInput"></param>
        /// <param name="sDelim"></param>
        /// <returns></returns>
        internal static int PieceLength(string sInput, string sDelim)
        {
            char[] cDelim = sDelim.ToCharArray();
            string[] cSplit = sInput.Split(cDelim);
            return cSplit.GetLength(0);
        }

        /// <summary>
        /// Corresponds to M's $$Piece function
        /// </summary>
        /// <param name="sInput"></param>
        /// <param name="sDelim"></param>
        /// <param name="nNumber"></param>
        /// <returns></returns>
        internal static string Piece(string sInput, string sDelim, int nNumber)
        {
            try
            {
                char[] cDelim = sDelim.ToCharArray();
                string[] cSplit = sInput.Split(cDelim);
                int nLength = cSplit.GetLength(0);
                if ((nLength < nNumber) || (nNumber < 1))
                    return "";
                return cSplit[nNumber - 1];
            }
            catch (Exception bmxEx)
            {
                string sMessage = bmxEx.Message + bmxEx.StackTrace;
                throw new BMXNetException(sMessage);
            }

        }

        internal static string Piece(string sInput, string sDelim, int nNumber, int nEnd)
        {
            try
            {
                if (nNumber < 0)
                    nNumber = 1;

                if (nEnd < nNumber)
                    return "";

                if (nEnd == nNumber)
                    return Piece(sInput, sDelim, nNumber);

                char[] cDelim = sDelim.ToCharArray();
                string[] cSplit = sInput.Split(cDelim);
                int nLength = cSplit.GetLength(0);
                if ((nLength < nNumber) || (nNumber < 1))
                    return "";

                //nNumber = 1-based index of the starting element to return
                //nLength = count of elements
                //nEnd = 1-based index of last element to return
                //nCount = number of elements past nNumber to return

                //convert nNumber to 0-based index:
                nNumber--;

                //convert nEnd to 0-based index;
                nEnd--;

                //Calculate nCount;
                int nCount = nEnd - nNumber + 1;

                //Adjust nCount for number of elements
                if (nCount + nNumber >= nLength)
                {
                    nCount = nLength - nNumber;
                }

                string sRet = string.Join(sDelim, cSplit, nNumber, nCount);
                return sRet;
            }
            catch (Exception bmxEx)
            {
                string sMessage = bmxEx.Message + bmxEx.StackTrace;
                throw new BMXNetException(sMessage);
            }
        }

        #endregion Piece Functions



        #region RPX Functions

        /// <summary>
        /// Given strInput = "13" builds "013" if nLength = 3.  Default for nLength is 3.
        /// </summary>
        /// <param name="strInput"></param>
        /// <returns></returns>
        internal protected string ADEBLDPadString(string strInput)
        {
            return ADEBLDPadString(strInput, 3);
        }

        /// <summary>
        /// Given strInput = "13" builds "013" if nLength = 3  Default for nLength is 3.
        /// </summary>
        /// <param name="strInput"></param>
        /// <param name="nLength">Default = 3</param>
        /// <returns></returns>
 

  
        internal protected string ADEBLDPadString(string strInput, int nLength ) //=3
        {
            return strInput.PadLeft(nLength, '0');
        }

        /// <summary>
        /// Concatenates zero-padded length of sInput to sInput
        /// Given "Hello" returns "004Hello"
        /// If nSize = 5, returns "00004Hello"
        /// Default for nSize is 3.
        /// </summary>
        /// <param name="sInput"></param>
        /// <returns></returns>
        internal protected string ADEBLDB(string sInput)
        {
            return ADEBLDB(sInput, 3);
        }

        /// <summary>
        /// Concatenates zero-padded length of sInput to sInput
        /// Given "Hello" returns "004Hello"
        /// If nSize = 5, returns "00004Hello"
        /// Default for nSize is 3.
        /// </summary>
        /// <param name="sInput"></param>
        /// <param name="nSize"></param>
        /// <returns></returns>
        internal protected string ADEBLDB(string sInput, int nSize) //=3
        {
            int nLen = sInput.Length;
            string sLen = this.ADEBLDPadString(nLen.ToString(), nSize);
            return sLen + sInput;
        }

        /// <summary>
        /// Build protocol header
        /// </summary>
        /// <param name="sWKID"></param>
        /// <param name="sWINH"></param>
        /// <param name="sPRCH"></param>
        /// <param name="sWISH"></param>
        /// <returns></returns>
        internal protected string ADEBHDR(string sWKID, string sWINH, string sPRCH, string sWISH)
        {
            string strResult;
            strResult = sWKID + ";" + sWINH + ";" + sPRCH + ";" + sWISH + ";";
            strResult = ADEBLDB(strResult);
            return strResult;
        }

        internal protected string ADEBLDMsg(string cHDR, string cRPC, string cParam)
        {
            string sMult = "";
            return ADEBLDMsg(cHDR, cRPC, cParam, ref sMult);
        }

        internal protected string ADEBLDMsg(string cHDR, string cRPC, string cParam, ref string cMult)
        {
            //Builds RPC message
            //TODO: Verify that this is still needed.  If this is needed, it should be
            //handled exclusively on the RPMS-side and allow TCP/IP to optimize the
            //transort
            string cMSG;
            string sBuild = "";
            string sPiece = "";
            int l;
            int nLength;

            if (cParam == "")
            {
                cMSG = "0" + cRPC;
            }
            else
            {
                l = PieceLength(cParam, "^");
                for (int j = 1; j <= l; j++)
                {
                    sPiece = Piece(cParam, "^", j);
                    nLength = sPiece.Length + 1;
                    sPiece = ADEBLDPadString(nLength.ToString()) + "0" + sPiece;
                    sBuild = sBuild + sPiece;
                }
                nLength = sBuild.Length;
                string sTotLen = ADEBLDPadString(nLength.ToString(), 5);
                if (cMult.Length > 0)
                {
                    cMSG = "1" + cRPC + "^" + sTotLen + sBuild;
                }
                else
                {
                    cMSG = "0" + cRPC + "^" + sTotLen + sBuild;
                }
            }
            cMSG = ADEBLDB(cMSG, 5);
            cMSG = cHDR + cMSG;
            return cMSG;
        }

        internal static int FindChar(byte[] c, char y)
        {
            int n = 0;
            int nRet = -1;
            for (n = 0; n < c.Length; n++)
            {
                if (y == (char)c[n])
                {
                    nRet = n;
                    break;
                }
            }

            return nRet;
        }

        internal static int FindChar(string s, char y)
        {
            int n = 0;
            int nRet = -1;
            foreach (char c in s)
            {
                if (y == c)
                {
                    nRet = n;
                    break;
                }
                n++;
            }
            return nRet;
        }

        

        /// <summary>
        /// Returns index of first instance of sSubString in sString.
        /// If sSubString not found, returns -1.
        /// </summary>
        /// <param name="sString"></param>
        /// <param name="sSubString"></param>
        /// <returns></returns>
        internal static int FindSubString(string sString, string sSubString)
        {
            int nFound = -1;
            int nLimit = sString.Length - sSubString.Length + 1;
            if (nLimit < 0)
                return -1;

            int nSubLength = sSubString.Length;
            for (int j = 0; j < nLimit; j++)
            {
                if (sString.Substring(j, nSubLength) == sSubString)
                {
                    nFound = j;
                    break;
                }
            }
            return nFound;
        }
        /*
    
        StreamWriter m_LogWriter;
        bool m_bLogging = false;

        public void StartLog()
        {
            try
            {
                if (m_bLogging)
                {
                    throw new Exception("Already logging.");
                }
                string sFile = "BMXLog " + DateTime.Now.DayOfYear.ToString() + " " +
                     DateTime.Now.Hour.ToString() + " " + DateTime.Now.Minute.ToString()
                     + " " + DateTime.Now.Second.ToString() + ".log";
                StartLog(sFile);
                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void StartLog(string LogFileName)
        {
            try
            {
                if (m_bLogging)
                {
                    throw new Exception("Already logging.");
                }
                m_LogWriter = File.AppendText(LogFileName);
                m_bLogging = true;
                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void StopLog()
        {
            try
            {
                //Close the writer and underlying file.
                if (m_bLogging == false)
                {
                    return;
                }
                m_LogWriter.Close();
                m_bLogging = false;
                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private static void Log(String logMessage, TextWriter w)
        {
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            w.WriteLine("  :");
            w.WriteLine("  :{0}", logMessage);
            w.WriteLine("-------------------------------");
            // Update the underlying file.
            w.Flush();
        }

   

        public bool Lock(string Variable)
        {
            return Lock(Variable, "", "");
        }

        public bool Lock(string Variable, string Increment)
        {
            return Lock(Variable, Increment, "");
        }

        /// <summary>
        /// Lock a local or global M variable
        /// Returns true if lock is obtained during TimeOut seconds
        /// Use + to increment, - to decrement lock.
        /// </summary>
        /// <param name="Variable"></param>
        /// <param name="Increment"></param>
        /// <param name="TimeOut"></param>
        /// <returns></returns>
        public bool Lock(string Variable, string Increment, string TimeOut)
        {
            try
            {
                string sContext = this.AppContext;
                this.AppContext = "BMXRPC";
                Variable = Variable.Replace("^", "~");
                string sRet = "0";
                bool bRet = false;
                string sParam = Variable + "^" + Increment + "^" + TimeOut;
                sRet = TransmitRPC("BMX LOCK", sParam);
                bRet = (sRet == "1") ? true : false;
                this.AppContext = sContext;
                return bRet;
            }
            catch (Exception ex)
            {
                string sMsg = ex.Message;
                return false;
            }
        }

        static ReaderWriterLock m_rwl = new ReaderWriterLock();
        private int m_nRWLTimeout = 30000; //30-second default timeout

        /// <summary>
        /// Returns a reference to the internal ReaderWriterLock member.
        /// </summary>
        public ReaderWriterLock BMXRWL
        {
            get
            {
                return m_rwl;
            }
        }

        /// <summary>
        /// Sets and returns the timeout in milliseconds for locking the transmit port.
        /// If the transmit port is unavailable an ApplicationException will be thrown.
        /// </summary>
        public int RWLTimeout
        {
            get
            {
                return m_nRWLTimeout;
            }
            set
            {
                m_nRWLTimeout = value;
            }
        }

        

        protected string EncodeSendString(String cSendString, String cMulti)
        {
            String encoded = null;

            int nLen = cSendString.Length;
            string sLen = nLen.ToString();
            sLen = sLen.PadLeft(5, '0');
            encoded = sLen + cSendString;

            nLen += 15;
            sLen = nLen.ToString();
            sLen = sLen.PadLeft(5, '0');

            encoded = "{BMX}" + sLen + encoded;
            encoded = encoded + cMulti;

            return encoded;
        }

        protected string DecodeReceiveString(String aString)
        {
            return aString;
        }


        protected String SendReceiveString(String sendString)
        {
            return this.SendReceiveString(sendString, "");
        }

        protected abstract String SendReceiveString(String sendString, String multi);

        public virtual string TransmitRPC(string sRPC, string sParam, int nLockTimeOut)
        {
            try
            {
                try
                {
                    if (!this.IsConnected)
                    {
                        throw new BMXNetException("BMXNetBroker.TransmitRPC failed because BMXNetBroker is not connected to RPMS.");
                    }

                    string priorAppContext = this.AppContext;

                    if (sRPC.StartsWith("BMX") && (this.AppContext != "BMXRPC"))
                    {
                        this.AppContext = "BMXRPC";
                    }

                    string sMult = "";
                    string sSend = ADEBLDMsg(m_cHDR, sRPC, sParam, ref sMult);
                    string strResult = SendReceiveString(sSend, sMult);
                    
                    this.AppContext = priorAppContext;
                    
                    return strResult;
                }
                catch (Exception ex)
                {
                    if (ex.Message == "Unable to write data to the transport connection.")
                    {
                        this.BeDisconnected();
                    }
                    throw ex;
                }
                finally
                {
                }
            }
            catch (ApplicationException aex)
            {
                // The writer lock request timed out.
                Debug.Write("TransmitRPC writer lock request timed out.\n");
                throw aex;
            }
            catch (Exception OuterEx)
            {
                throw OuterEx;
            }
        }

        public virtual void BeDisconnected() {

            //TAE
        }

        public string TransmitRPC(string sRPC, string sParam)
        {
            try
            {
                return TransmitRPC(sRPC, sParam, m_nRWLTimeout);
            }
            catch (ApplicationException aex)
            {
                throw aex;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public abstract string GetLoginFacility(String aDuz);


        #endregion RPX Functions

     
        /// <summary>
        /// Gets/sets the Kernel Application context
        /// Throws an exception if unable to set the context. 
        /// </summary>
        public string AppContext
        {
            get
            {
                return m_cAppContext;
            }
            set
            {

                if (m_cAppContext == value)
                    return;

                //Send the changed context to RPMS
                if ((this.IsConnected) && (value != null) && (value != ""))
                {
                    try
                    {
                        string sRPC = ADEEncryp(value);
                        string sAuthentication = TransmitRPC("XWB CREATE CONTEXT", sRPC);

                        if (BMXNetBroker.FindSubString(sAuthentication, "does not have access to option") > -1)
                        {
                            throw new BMXNetException(sAuthentication);
                        }

                    }
                    catch (Exception ex)
                    {
                        Debug.Write(ex.Message);
                        throw ex;
                    }
                }
                m_cAppContext = value;
            }
        }


        public string DUZ
        {
            get
            {
                return m_cDUZ;
            }
            set { this.m_cDUZ = value; }
        }
        */

        #region Encryption Keys

        private string[] m_sKey = new string[]
			{
				@"wkEo-ZJt!dG)49K{nX1BS$vH<&:Myf*>Ae0jQW=;|#PsO`'%+rmb[gpqN,l6/hFC@DcUa ]z~R}""V\iIxu?872.(TYL5_3",
				@"rKv`R;M/9BqAF%&tSs#Vh)dO1DZP> *fX'u[.4lY=-mg_ci802N7LTG<]!CWo:3?{+,5Q}(@jaExn$~p\IyHwzU""|k6Jeb",
				@"\pV(ZJk""WQmCn!Y,y@1d+~8s?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3-(o|J9XUE7k\TlqSb>anG",
				@"xVa1']_GU<X`|\NgM?LS9{""jT%s$}y[nvtlefB2RKJW~(/cIDCPow4,>#zm+:5b@06O3Ap8=*7ZFY!H-uEQk; .q)i&rhd",
				@"I]Jz7AG@QX.""%3Lq>METUo{Pp_ |a6<0dYVSv8:b)~W9NK`(r'4fs&wim\kReC2hg=HOj$1B*/nxt,;c#y+![?lFuZ-5D}",
				@"Rr(Ge6F Hx>q$m&C%M~Tn,:""o'tX/*yP.{lZ!YkiVhuw_<KE5a[;}W0gjsz3]@7cI2\QN?f#4p|vb1OUBD9)=-LJA+d`S8",
				@"I~k>y|m};d)-7DZ""Fe/Y<B:xwojR,Vh]O0Sc[`$sg8GXE!1&Qrzp._W%TNK(=J 3i*2abuHA4C'?Mv\Pq{n#56LftUl@9+",
				@"~A*>9 WidFN,1KsmwQ)GJM{I4:C%}#Ep(?HB/r;t.&U8o|l['Lg""2hRDyZ5`nbf]qjc0!zS-TkYO<_=76a\X@$Pe3+xVvu",
				@"yYgjf""5VdHc#uA,W1i+v'6|@pr{n;DJ!8(btPGaQM.LT3oe?NB/&9>Z`-}02*%x<7lsqz4OS ~E$\R]KI[:UwC_=h)kXmF",
				@"5:iar.{YU7mBZR@-K|2 ""+~`M%8sq4JhPo<_X\Sg3WC;Tuxz,fvEQ1p9=w}FAI&j/keD0c?)LN6OHV]lGy'$*>nd[(tb!#",
		};
        #endregion Encryption Keys

        #endregion

        public virtual string RegisterWindowsIdentityForWindowsAuthenication(WindowsIdentity windowsIdentity)
        {
            throw new NotSupportedException();
        }

        #region IEncryptionProvider Members

        public virtual string Encrypt(string aString)
        {
            throw new NotSupportedException();
        }

        public virtual string Decrypt(string aString)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
        
}
