using Serilog;
using Serilog.Events;
using Serilog.Formatting;
using System;
using System.IO;
using System.Security.Policy;

namespace Logger
{
    public static class Log
    {
        private static readonly ILogger logger;
        public static event Action<string> ShowMsg; // 记录日志事件

        static Log()
        {
            string logpath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Logs\Log_{DateTime.Now:yyyy-MM-dd}.html");
            logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.File(new HtmlFormatter(), logpath,
                rollingInterval: RollingInterval.Day,
                rollOnFileSizeLimit: true,
                retainedFileCountLimit: 7,
                fileSizeLimitBytes: 1000 * 1024)
                .CreateLogger();
        }

        public static void Error(string message)
        {
            ShowMsg?.Invoke(message);
            logger.Error(message);
        }

        public static void FunError(Exception ex, string funName)
        {
            ShowMsg?.Invoke(funName + " — FunErr — " + ex.Message);
            logger.Error(funName + " — FunErr — " + ex.Message);
        }

        public static void Info(string message)
        {
            ShowMsg?.Invoke(message);
            logger.Information(message);
        }

        public static void Debug(string message)
        {
            ShowMsg?.Invoke(message);
            logger.Debug(message);
        }

        public static void Warning(string message)
        {
            ShowMsg?.Invoke(message);
            logger.Warning(message);
        }

        public static void Fatal(string message)
        {
            ShowMsg?.Invoke(message);
            logger.Fatal(message);
        }
    }

    public class HtmlFormatter : ITextFormatter
    {
        public void Format(LogEvent logEvent, TextWriter output)
        {
            string levelColor = GetLevelColor(logEvent.Level);
            string message = logEvent.RenderMessage();

            output.WriteLine($"<div style=\"color: {levelColor};\">");
            output.WriteLine($"<p>[{logEvent.Timestamp:yyyy-MM-dd HH:mm:ss}] [{logEvent.Level}] {message}</p>");
            output.WriteLine("</div>");
        }

        private string GetLevelColor(LogEventLevel level)
        {
            switch (level)
            {
                case LogEventLevel.Debug:
                    return "gray";
                case LogEventLevel.Information:
                    return "black";
                case LogEventLevel.Warning:
                    return "orange";
                case LogEventLevel.Error:
                    return "red";
                case LogEventLevel.Fatal:
                    return "purple";
                default:
                    return "black";
            }
        }
    }
}
