namespace Sonex.Client.Helpers;

using Sonex.Client.Dialogs;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

public static class LogerSender
{
    private static readonly object Sync = new();
    private static readonly HttpClient HttpClient = new()
    {
        Timeout = TimeSpan.FromSeconds(3)
    };

    private static bool _started;

    /// <summary>
    /// Uruchamia wysylke zaleglych logow w tle.
    /// Funkcja nigdy nie blokuje startu aplikacji i nie wyrzuca wyjatku na zewnatrz.
    /// </summary>
    public static void SendLogs()
    {
        lock (Sync)
        {
            if (_started)
                return;

            _started = true;
        }

        _ = Task.Run(async () =>
        {
            try
            {
                await SendLogsInternalAsync();
            }
            catch
            {
            }
            finally
            {
                lock (Sync)
                {
                    _started = false;
                }
            }
        });
    }

    /// <summary>
    /// Skanuje folder Logs i wysyla wszystkie pliki JSON, ktore nie sa jeszcze oznaczone jako wyslane.
    /// </summary>
    private static async Task SendLogsInternalAsync()
    {
        string endpoint = Config.GetStringValue("LOGS_ENDPOINT", string.Empty).Trim();
        if (string.IsNullOrWhiteSpace(endpoint))
            return;

        if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri))
            return;

        string logsPath = Logger.GetLogsDirectoryPath();
        if (!Directory.Exists(logsPath))
            return;

        string[] files;

        try
        {
            files = Directory.GetFiles(logsPath, "*.json", SearchOption.TopDirectoryOnly);
        }
        catch
        {
            return;
        }

        Array.Sort(files, StringComparer.OrdinalIgnoreCase);

        foreach (string filePath in files)
        {
            try
            {
                if (filePath.EndsWith(".sended.json", StringComparison.OrdinalIgnoreCase))
                    continue;

                string json = await File.ReadAllTextAsync(filePath, Encoding.UTF8);
                if (string.IsNullOrWhiteSpace(json))
                    continue;

                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                using var response = await HttpClient.PostAsync(uri, content);

                if (!response.IsSuccessStatusCode)
                    continue;

                RenameToSended(filePath);
            }
            catch
            {
            }
        }
    }

    /// <summary>
    /// Oznacza poprawnie wyslany plik przez zmiane rozszerzenia z .json na .sended.json.
    /// </summary>
    private static void RenameToSended(string filePath)
    {
        try
        {
            if (!filePath.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
                return;

            string sentFilePath = filePath[..^".json".Length] + ".sended.json";
            File.Move(filePath, sentFilePath, overwrite: true);
        }
        catch
        {
        }
    }
}
