using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Text.Json;

namespace qtc_net_client_2.Services
{
    public class LoggingService : IDisposable
    {
        private DateTime LogDate { get; set; }
        private string LogFilePath { get; set; }
        private StreamWriter LogFile { get; set; }
        public LoggingService()
        {
            LogDate = DateTime.Now;
            LogFilePath = $"./Logs/QtCClientLog_{LogDate.ToString("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)
        {
            Debug.WriteLine($"({DateTime.Now.ToLocalTime().ToString("hh:mm")}) {message}");
            LogFile.WriteLine($"({DateTime.Now.ToLocalTime().ToString("hh:mm")}) {message}");
        }

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

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

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