using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

// 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 sealed class TelegramLogger : ILogger, IDisposable
    {
        private readonly string _categoryName;
        private readonly TelegramLoggerOptions _options;
        private readonly HttpClient _httpClient;
        private readonly Channel<string> _logChannel;
        private readonly CancellationTokenSource _cts = new();
        private readonly Task _processingTask;

        private const int MaxQueueSize = 1000;

        public event EventHandler<Exception> OnException;

        public TelegramLogger(string categoryName, TelegramLoggerOptions options)
        {
            _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName));
            _options = options ?? throw new ArgumentNullException(nameof(options));

            _httpClient = new HttpClient();

            _logChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(MaxQueueSize)
            {
                FullMode = BoundedChannelFullMode.DropOldest,
                SingleReader = true,
                SingleWriter = false
            });

            _processingTask = Task.Run(() => ProcessLogQueueAsync(_cts.Token), _cts.Token);
        }

        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
            {
                var sb = new StringBuilder(256);
                sb.Append('[').Append(DateTime.UtcNow.ToString("u")).Append("] ");
                sb.Append('[').Append(logLevel).Append("] ");
                sb.Append(_categoryName).Append(": ");
                sb.Append(formatter(state, exception));

                if (exception != null)
                {
                    sb.AppendLine().Append("Exception: ").Append(exception);
                }

                _logChannel.Writer.TryWrite(sb.ToString());
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        private async Task ProcessLogQueueAsync(CancellationToken token)
        {
            try
            {
                var url = $"https://api.telegram.org/bot{_options.BotToken}/sendMessage";

                await foreach (var message in _logChannel.Reader.ReadAllAsync(token))
                {
                    try
                    {
                        var payload = new { chat_id = _options.ChatId, text = message };
                        using var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");

                        var response = await _httpClient.PostAsync(url, content, token).ConfigureAwait(false);

                        if (!response.IsSuccessStatusCode)
                        {
                            var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                            OnException?.Invoke(this, new Exception($"Telegram API failed: {response.StatusCode} {error}"));
                        }
                    }
                    catch (Exception ex)
                    {
                        OnException?.Invoke(this, ex);
                    }
                }
            }
            catch (OperationCanceledException) 
            {
                // normal shutdown
            }
        }

        public void Dispose()
        {
            _cts.Cancel();
            _logChannel.Writer.Complete();

            try
            {
                _processingTask.Wait(); 
            }
            catch 
            {
                // Do nothing
            }

            _cts.Dispose();
            _httpClient.Dispose();
        }
    }
}
