using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Xml.Linq;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

namespace EonaCat.Logger.EonaCatCoreLogger
{
    public class XmlFileLogger : ILogger
    {
        private readonly string _categoryName;
        private readonly XmlFileLoggerOptions _options;
        private readonly string _filePath;
        private readonly LoggerScopedContext _context = new();

        public bool IncludeCorrelationId { get; set; }

        public event EventHandler<Exception> OnException;


        public XmlFileLogger(string categoryName, XmlFileLoggerOptions options)
        {
            _categoryName = categoryName;
            _options = options;
            _filePath = Path.Combine(_options.LogDirectory, _options.FileName);
            Directory.CreateDirectory(_options.LogDirectory);
            IncludeCorrelationId = options.IncludeCorrelationId;
        }

        public void SetContext(string key, string value) => _context.Set(key, value);
        public void ClearContext() => _context.Clear();
        public string GetContext(string key) => _context.Get(key);

        public IDisposable BeginScope<TState>(TState state) => null;

        public bool IsEnabled(LogLevel logLevel) => _options.IsEnabled;

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
            Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel) || formatter == null)
            {
                return;
            }

            try
            {
                if (IncludeCorrelationId)
                {
                    var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
                    _context.Set("CorrelationId", correlationId);
                }

                var logElement = new XElement("log",
                    new XElement("timestamp", DateTime.UtcNow.ToString("o")),
                    new XElement("level", logLevel.ToString()),
                    new XElement("category", _categoryName),
                    new XElement("message", formatter(state, exception))
                );

                var context = _context.GetAll();
                if (context.Count > 0)
                {
                    var contextElement = new XElement("context");
                    foreach (var item in context)
                    {
                        contextElement.Add(new XElement(item.Key, item.Value));
                    }
                    logElement.Add(contextElement);
                }

                if (exception != null)
                {
                    logElement.Add(new XElement("exception", exception.ToString()));
                }

                File.AppendAllText(_filePath, logElement.ToString() + Environment.NewLine);
            }
            catch (Exception e)
            {
                OnException?.Invoke(this, e);
            }
        }
    }
}
