//******************************************************************************//
// UDPPacketsParser.cs
// 12/4/2023
//
// RAYTHEON PROPRIETARY: THIS DOCUMENT CONTAINS DATA OR INFORMATION
// PROPRIETARY TO RAYTHEON COMPANY AND IS RESTRICTED TO USE ONLY BY PERSONS
// AUTHORIZED BY RAYTHEON COMPANY IN WRITING TO USE IT. DISCLOSURE TO
// UNAUTHORIZED PERSONS WOULD LIKELY CAUSE SUBSTANTIAL COMPETITIVE HARM TO
// RAYTHEON COMPANY'S BUSINESS POSITION. NEITHER SAID DOCUMENT NOR ITS
// CONTENTS SHALL BE FURNISHED OR DISCLOSED TO OR COPIED OR USED BY PERSONS
// OUTSIDE RAYTHEON COMPANY WITHOUT THE EXPRESS WRITTEN APPROVAL OF RAYTHEON
// COMPANY.
//
// THIS PROPRIETARY NOTICE IS NOT APPLICABLE IF DELIVERED TO THE U.S. GOVERNMENT
//
// UNPUBLISHED WORK - COPYRIGHT RAYTHEON COMPANY.
//
// WARNING: THIS DOCUMENT CONTAINS TECHNICAL DATA AND / OR TECHNOLOGY WHOSE
// EXPORT OR DISCLOSURE TO NON-U.S. PERSONS, WHEREVER LOCATED, IS RESTRICTED
// BY THE INTERNATIONAL TRAFFIC IN ARMS REGULATIONS (ITAR) (22 C.F.R. SECTION
// 120-130) OR THE EXPORT ADMINISTRATION REGULATIONS (EAR) (15 C.F.R. SECTION
// 730-774). THIS DOCUMENT CANNOT BE EXPORTED (E.G., PROVIDED TO A SUPPLIER
// OUTSIDE OF THE UNITED STATES) OR DISCLOSED TO A NON-U.S. PERSON, WHEREVER
// LOCATED, UNTIL A FINAL JURISDICTION AND CLASSIFICATION DETERMINATION HAS
// BEEN COMPLETED AND APPROVED BY RAYTHEON, AND ANY REQUIRED U.S. GOVERNMENT
// APPROVALS HAVE BEEN OBTAINED. VIOLATIONS ARE SUBJECT TO SEVERE CRIMINAL
// PENALTIES.
//
// DOD 5220.22-M, INDUSTRIAL SECURITY MANUAL, CHAPTER 5, SECTION 1 THROUGH 9 :
// FOR CLASSIFIED DOCUMENTS FOLLOW THE PROCEDURES IN OR DOD 5200.1-R,
// INFORMATION SECURITY PROGRAM, CHAPTER 6. FOR UNCLASSIFIED, LIMITED DOCUMENTS
// DESTROY BY ANY  METHOD THAT WILL PREVENT DISCLOSURE OF CONTENTS OR
// RECONSTRUCTION OF THE DOCUMENT.
// POC: Alex Kravchenko (1118268)
//******************************************************************************//
using Raytheon.LogDashboard.Model;
using System;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Xml;
using Raytheon.LogDashboard.Helpers;
using Settings = Raytheon.LogDashboard.Model.Settings;
using GalaSoft.MvvmLight.Messaging;

namespace Raytheon.LogDashboard.Parsers
{
    public class UDPPacketsParser : PacketsParser
    {
        private UdpClient udpClient;
        private IPEndPoint remoteIpEndPoint;

        public int Port { get; set; }

        public UDPPacketsParser(string name, bool isAutoSave)
            : base(name, isAutoSave)
        {
        }

        public UDPPacketsParser(string name, string address, int port, bool isAutoSave)
            : this(name, isAutoSave)
        {
            Address = address;
            Port = port;
        }

        /// <summary>
        /// initialize UDP parser
        /// </summary>
        /// <returns></returns>
		public override bool Init()
        {
            try
            {
                base.Init();
                udpClient = new UdpClient(Port);
                remoteIpEndPoint = new IPEndPoint(IPAddress.Any, Port);
                IsInitialized = true;
                return IsInitialized;
            }
            catch(SocketException socketException)
            {
                Logger.Warn(socketException, "An error occurred in UDPPacketsParser ctor.");
                Messenger.Default.Send($"Port {Port} is busy!", "DisplayCustomMessage");

                IsInitialized = false;
                return IsInitialized;
            }
            catch(Exception e)
            {
                Logger.Warn(e, "An error occurred in UDPPacketsParser ctor.");
                Messenger.Default.Send($"An error occurred while connect to port {Port}.\n{e.Message}", "DisplayCustomMessage");
                IsInitialized = false;
                return IsInitialized;
            }
        }

        /// <summary>
        /// read individual message
        /// </summary>
        /// <returns></returns>
        public override LogMessage GetLog()
        {
            LogMessage log = null;
            string incomingLog = string.Empty;

            if(udpClient == null)
            {
                return null;
            }

            try
            {
                // getting bytes 
                byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint);
                if(IgnoredIPs.Any(x => x.IsActive && x.IP.Contains(remoteIpEndPoint.Address.ToString())))
                {
                    return null;
                }

                // converting bytes to string
                incomingLog = Encoding.GetString(receiveBytes);

                log = ReadXmlLog(incomingLog);
                log.Address = Settings.Instance.IsSeparateIPLoggersByPort ? $"{remoteIpEndPoint.Address}:{Port}" : remoteIpEndPoint.Address.ToString();
                log.Port = Port;
            }
            catch(SocketException)
            {
                return null;
            }
            catch(Exception e)
            {
                log = new LogMessage
                {
                    Logger = "UDP Logger",
                    Address = Settings.Instance.IsSeparateIPLoggersByPort ? $"{remoteIpEndPoint.Address}:{Port}" : remoteIpEndPoint.Address.ToString(),
                    Thread = -1,
                    Message = $"An error occurred while parsing log: {incomingLog}. {Environment.NewLine} Exception: {e}",
                    Time = DateTime.Now,
                    Level = DashboardLogLevel.Error,
                    ExecutableName = "LogDashboard"
                };

                Logger.Warn(e, "An error occurred while parsing log.");
            }

            if(IsAutoSave)
            {
                Messenger.Default.Send(log, "PersistLogMessage");
            }
            return log;
        }

        /// <summary>
        /// reads XML log in log4j format
        /// </summary>
        /// <param name="xmlFragment"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        private LogMessage ReadXmlLog(string xmlFragment)
        {
            LogMessage log = new LogMessage();

            using(XmlReader reader = new XmlTextReader(xmlFragment, XmlNodeType.Element, XmlContext) { WhitespaceHandling = WhitespaceHandling.Significant })
            {
                reader.Read();
                if(reader.MoveToContent() != XmlNodeType.Element || reader.Name != "log4j:event")
                {
                    throw new Exception("The Log Event is not a valid log4j Xml block.");
                }

                log.Logger = reader.GetAttribute("logger");
                log.Level = (DashboardLogLevel)Enum.Parse(typeof(DashboardLogLevel), reader.GetAttribute("level").ToLower().FirstCharToUpper());
                log.Thread = int.Parse(reader.GetAttribute("thread"));

                if(long.TryParse(reader.GetAttribute("timestamp"), out long timeStamp))
                {
                    log.Time = UnixTimeStampToDateTime(timeStamp).ToLocalTime();
                }

                int eventDepth = reader.Depth;
                reader.Read();
                while(reader.Depth > eventDepth)
                {
                    if(reader.MoveToContent() == XmlNodeType.Element)
                    {
                        switch(reader.Name)
                        {
                            case "log4j:message":
                                log.Message = reader.ReadString();
                                break;

                            case "log4j:throwable":
                                log.Message += Environment.NewLine + reader.ReadString();
                                break;
                            case "log4j:properties":
                                reader.Read();
                                while(reader.MoveToContent() == XmlNodeType.Element
                                       && reader.Name == "log4j:data")
                                {
                                    string name = reader.GetAttribute("name");
                                    string value = reader.GetAttribute("value");
                                    if(!string.IsNullOrEmpty(name) && name == "log4japp" && !string.IsNullOrEmpty(value) && value.Contains(".exe"))
                                    {
                                        log.ExecutableName = value.Substring(0, value.IndexOf(".exe", StringComparison.Ordinal));
                                    }

                                    reader.Read();
                                }

                                break;
                        }
                    }
                    reader.Read();
                }
            }
            return log;
        }

        public override void Dispose()
        {
            base.Dispose();
            try
            {
                udpClient?.Close();
                udpClient?.Dispose();
                udpClient = null;
            }
            catch(Exception e)
            {
                Logger.Warn(e, "Dispose error");
            }
        }
    }
}
