using log4net;
using System;

namespace SystemX.Net.Platform.Common.Util
{
    public class LogMessage
    {
        public enum LogMessageLevel
        {
            NONE = 0,
            FATAL,
            DEBUG,
            INFO,
            LAST
        };

        public delegate void MessageEventHandlerOutput(string strMessage, ConsoleColor csColor = ConsoleColor.White, LogMessageLevel logLevel = LogMessageLevel.DEBUG);

        static public class MessageOutput
        {
            private static ILog logger => Log4NetWrapper.Logger;
            static public LogMessageLevel PrintLogLevel { get; set; } = LogMessageLevel.DEBUG;
            static public MessageEventHandlerOutput UEventOutput;
            static public void ConsoleWrite(string strMessage, ConsoleColor csColor = ConsoleColor.White, LogMessageLevel logLevel = LogMessageLevel.DEBUG)
            {
                try
                {
                    if (PrintLogLevel >= logLevel)
                    {
                        Console.ForegroundColor = csColor;
                        Console.WriteLine(strMessage);
                        Console.ResetColor();
                        UEventOutput?.Invoke(strMessage, csColor, logLevel);
                        switch (logLevel)
                        {
                            case LogMessageLevel.FATAL:
                                logger.Error(strMessage);

                                //WriteEventLogEntry(strMessage);
                                break;
                            case LogMessageLevel.DEBUG:
                                logger.Debug(strMessage);
                                break;
                            default:
                                logger.Info(strMessage);
                                break;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        private static void WriteEventLogEntry(string message)
        {
            // Create an instance of EventLog
            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

            // Check if the event source exists. If not create it.
            if (!System.Diagnostics.EventLog.SourceExists("CP-ServerX"))
            {
                System.Diagnostics.EventLog.CreateEventSource("CP-ServerX", "SystemX");
            }

            // Set the source name for writing log entries.
            eventLog.Source = "CP-ServerX";

            // Create an event ID to add to the event log
            int eventID = 2051;

            // Write an entry to the event log.
            eventLog.WriteEntry(message,
                                System.Diagnostics.EventLogEntryType.Error,
                                eventID);

            // Close the Event Log
            eventLog.Close();
        }
    }
}
