using EonaCat.Logger.LogClient.Models;
using EonaCat.Logger.Managers;
using System;
using System.Collections.Generic;
using System.Text;

namespace EonaCat.Logger.LogClient
{
    public class LogCentralEonaCatAdapter : IDisposable
    {
        private readonly LogCentralClient _client;
        private readonly LoggerSettings _logSettings;

        public LogCentralEonaCatAdapter(LoggerSettings logSettings, LogCentralClient client)
        {
            _client = client;
            _logSettings = logSettings;
            _logSettings.OnLog += LogSettings_OnLog;
        }

        private void LogSettings_OnLog(EonaCatCoreLogger.Models.EonaCatLogMessage e)
        {
            var entry = new LogEntry
            {
                Level = (int)MapLogLevel(e.LogType),
                Category = e.Category ?? "General",
                Message = e.Message,
                Properties = new Dictionary<string, object>
            {
                { "Source", e.Origin ?? "Unknown" }
            }
            };

            if (e.Exception != null)
            {
                entry.Exception = e.Exception.ToString();
                entry.StackTrace = e.Exception.StackTrace;
            }

            _client.Log(entry);
        }

        private static LogLevel MapLogLevel(ELogType logType)
        {
            return logType switch
            {
                ELogType.TRACE => LogLevel.Trace,
                ELogType.DEBUG => LogLevel.Debug,
                ELogType.INFO => LogLevel.Information,
                ELogType.WARNING => LogLevel.Warning,
                ELogType.ERROR => LogLevel.Error,
                ELogType.CRITICAL => LogLevel.Critical,
                ELogType.TRAFFIC => LogLevel.Traffic,
                _ => LogLevel.Information
            };
        }

        public void Dispose()
        {
            _logSettings.OnLog -= LogSettings_OnLog;
            GC.SuppressFinalize(this);
        }
    }
}
