using EonaCat.LogStack.Configuration;
using EonaCat.LogStack.Extensions;
using EonaCat.LogStack.LogClient.Models;
using System;
using System.Collections.Generic;

// 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.LogStack.LogClient
{
    public class LogCentralEonaCatAdapter : IDisposable
    {
        private readonly LogCentralClient _client;
        private LogBuilder _logBuilder;

        public LogCentralEonaCatAdapter(LogBuilder logBuilder, LogCentralClient client)
        {
            _client = client;
            _logBuilder.OnLog += LogSettings_OnLog;
        }

        private void LogSettings_OnLog(object sender, LogMessage e)
        {
            var entry = new LogEntry
            {
                Level = e.Level.ToString().ToLower(),
                Message = e.Message,
                Properties = new Dictionary<string, object>
                {
                    { "Source", e.Origin ?? "Unknown" },
                    { "Category", e.Category ?? "General" }
                }.ToJson()
            };

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

            _client.LogAsync(entry).ConfigureAwait(false);
        }
        private static LogLevel MapLogLevel(Core.LogLevel logType)
        {
            return logType switch
            {
                Core.LogLevel.Trace => LogLevel.Trace,
                Core.LogLevel.Debug => LogLevel.Debug,
                Core.LogLevel.Information => LogLevel.Information,
                Core.LogLevel.Warning => LogLevel.Warning,
                Core.LogLevel.Error => LogLevel.Error,
                Core.LogLevel.Critical => LogLevel.Critical,
                _ => LogLevel.Information
            };
        }

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