using Pulsar.Client.Networking;
using Pulsar.Common.Messages;
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using static System.Net.WebRequestMethods;

namespace Pulsar.Client.LoggingAPI
{
    public class UniversalDebugLogger : TraceListener
    {
        // public static byte[] EncryptionKey { get; private set; }
        private static PulsarClient _client;

        public static void Initialize(PulsarClient c)
        {
            //try
            //{
            //    string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Logs");

            //    if (!Directory.Exists(path))
            //    {
            //        Directory.CreateDirectory(path);
            //    }

            //    // EncryptionKey = new byte[16];
            //    // using (var rng = new RNGCryptoServiceProvider())
            //    // {
            //    //     rng.GetBytes(EncryptionKey);
            //    // }

            //    string filePath = Path.Combine(path, "plog.txt");
            //    if (!File.Exists(filePath))
            //    {
            //        using (File.Create(filePath)) { }
            //    }
            //}
            //catch (Exception)
            //{
            //}

            _client = c;
        }

        public static void SendLogToServer(string logMessage)
        {
            if (_client != null && _client.Connected)
            {
                if (!IsBlacklistedMessage(logMessage))
                {
                    _client.Send(new GetDebugLog { Log = logMessage });
                }
            }
        }

        internal static bool IsUiAutomationLog(string message)
        {
            if (string.IsNullOrEmpty(message))
                return false;

            if (message.IndexOf("MS.Internal.Automation", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("System.Windows.Automation", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("UIAutomationClient", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("AutomationProxies", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("ElementNotAvailableException", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("ElementNotEnabledException", StringComparison.OrdinalIgnoreCase) >= 0 ||
                message.IndexOf("NoClickablePointException", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                return true;
            }

            if (message.IndexOf("L'op\u00E9ration n'est pas valide en raison de l'\u00E9tat actuel de l'objet", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                return true;
            }

                    if (message.IndexOf("L'\u00E9l\u00E9ment cible correspond \u00E0 une interface utilisateur", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        return true;
                    }

                    if (message.IndexOf("The target element corresponds to a user interface that is no longer available", StringComparison.OrdinalIgnoreCase) >= 0)
                    {
                        return true;
                    }

            if (message.IndexOf("L'E9lE9ment cible correspond E0 une interface utilisateur", StringComparison.OrdinalIgnoreCase) >= 0)
            {
                return true;
            }

            return false;
        }

        private static bool IsBlacklistedMessage(string message)
        {
            if (string.IsNullOrEmpty(message))
                return false;

            if (IsUiAutomationLog(message))
            {
                return true;
            }

            var blacklistedPatterns = new[]
            {
                "HRESULT: [0x887A0027]",
                "DXGI_ERROR_WAIT_TIMEOUT",
                "WaitTimeout",
                "The timeout value has elapsed and the resource is not yet available",
                "SharpDX.SharpDXException",
                "SharpDX.DXGI",
                "SharpDX.Result.CheckError()",
                "Waiting for frame requests. Buffer size:",
                "Received packet: GetDesktop",
                "Capture FPS:",
                "Buffer size:",
                "Pending requests:",
                "Value does not fall within the expected range.",
                "Accessibility.IAccessible.get_accChild",
                "System.Security.SecurityException: Requested registry access is not allowed"
            };

            foreach (var pattern in blacklistedPatterns)
            {
                if (message.Contains(pattern))
                {
                    return true;
                }
            }

            return false;
        }

        public override void WriteLine(string message)
        {
            try
            {
                    // string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Logs", "plog.txt");
                    // using (StreamWriter writer = new StreamWriter(path, true))
                    // {
                    //     writer.WriteLine(message);
                    // }
            }
            catch (Exception)
            {
            }
        }

        public override void Write(string message)
        {
        }
    }
}
