using Serilog;
using Serilog.Core;

namespace InABox.Avalonia
{
    public enum LogType
    {
        Query,
        Save,
        Delete,
        Validate,
        UIUpdate,
        BackgroundProcess
    }
    
    public static class MobileLogging
    {

        private static Logger _logger = null;

        private static string _logfilenameincludingpath;

        public delegate void ExceptionHandler(Exception ex, string? tag);

        public static event ExceptionHandler? LogException;
        
        private static Logger CheckLogger()
        {
            if (_logger == null)
            {
                var libraryPath = OperatingSystem.IsIOS()
                    ? Environment.GetFolderPath(Environment.SpecialFolder.Resources)
                    : Environment.GetFolderPath(Environment.SpecialFolder.Personal);


                var filename = $"{DateTime.Today:yyyy-MMM-dd}.prsmobile";
                _logfilenameincludingpath = Path.Combine(libraryPath, filename);
                
                var files = Directory.GetFiles(libraryPath, "*.prsmobile");
                foreach (var file in files)
                {
                    if (!String.Equals(filename.ToUpper(), Path.GetFileName(file).ToUpper()))
                        File.Delete(file);
                }

                _logger = new LoggerConfiguration()
                    .WriteTo.File(_logfilenameincludingpath)
                    .CreateLogger();
            }
            return _logger;
        }
        
        public static void Log(LogType type, string entitytype, string message, string page)
        {
            CheckLogger()
                .Information("{Type} {Entity} {Message} {Page}", type, entitytype, message, page);
        }
        
        public static void Log(string message)
        {
            CheckLogger()
                .Information("{Log}", message);
        }
        
        public static void LogError(string message)
        {
            CheckLogger()
                .Error("{Log}", message);
        }

        public static void Log(Exception exception, String tag = "")
        {
            LogException?.Invoke(exception, tag);
        }

        public static void LogExceptionMessage(Exception exception, string tag = "")
        {
            CheckLogger();
            if (String.IsNullOrWhiteSpace(tag))
                _logger.Error("{Message} {StackTrace}",exception.Message, exception.StackTrace);
            else
                _logger.Error("{Tag} {Message} {StackTrace}", tag, exception.Message, exception.StackTrace);
        }
        
        public static String ReadLog()
        {
            CheckLogger();
            return File.Exists(_logfilenameincludingpath)
                ? File.ReadAllText(_logfilenameincludingpath)
                : "";
        }
        
        
    }

}
