using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Abstractions;

namespace QtCNETAPI.Services
{
    public class LoggingService : IDisposable, ILogger
    {
        private DateTime LogDate { get; set; }
        private string LogFilePath { get; set; }
        private StreamWriter LogFile { get; set; }
        public LoggingService()
        {
            LogDate = DateTime.Now;
            LogFilePath = $"./Logs/QtCClientLog_{LogDate:ddMMyyy-hhmm}.log";

            // create log file

            if (!Directory.Exists("./Logs")) Directory.CreateDirectory("./Logs");
            LogFile = new StreamWriter(File.Create(LogFilePath));

            Debug.WriteLine($"Log File Created At {LogFilePath}");
        }

        public void LogString(string message)
        {
            try
            {
                Debug.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {message}");
                LogFile.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {message}");
            } catch (ObjectDisposedException)
            {
            }
        }

        public void LogModel<T>(T model)
        {
            try
            {
                // serialize the model as json
                string modelSerialized = JsonSerializer.Serialize(model, options: new JsonSerializerOptions { WriteIndented = true });

                // log it
                Debug.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {modelSerialized}");
                LogFile.WriteLine($"({DateTime.Now.ToLocalTime():hh:mm}) {modelSerialized}");
            } catch (ObjectDisposedException)
            {
            }
        }

        public void Dispose()
        {
            LogFile.WriteLine("--- END OF LOG ---");
            LogFile.Close();
            LogFile.Dispose();
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            try
            {
                // format message
                string message = $"({DateTime.Now.ToLocalTime():hh:mm}) [{logLevel}] {formatter(state, exception)}";

                // log it
                Debug.WriteLine(message);
                LogFile.WriteLine(message);
            } catch (ObjectDisposedException)
            {
            }
        }

        public bool IsEnabled(LogLevel logLevel) => true;
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull => default!;
    }

    public class LoggingServiceProvider(LoggingService? loggingService = null) : ILoggerProvider
    {
        public ILogger CreateLogger(string categoryName)
        {
            if (loggingService != null) return loggingService;
            else return new LoggingService();
        }

        public void Dispose() { }
    }
}
