using System;
using System.IO;
using Serilog;
using Serilog.Events;

namespace MarcusLaw.OutlookAddin.Core.Logging
{
    public static class LoggerFactory
    {
        private const string OutputTemplate =
            "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}";

        public static ILogger Init()
            => Init(DefaultLogDirectory());

        public static ILogger Init(string logDirectory)
        {
            if (string.IsNullOrWhiteSpace(logDirectory)) throw new ArgumentException("logDirectory required", nameof(logDirectory));

            Directory.CreateDirectory(logDirectory);

            var path = Path.Combine(logDirectory, "addin-.log");

            var logger = new LoggerConfiguration()
                .MinimumLevel.Information()
                .MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.File(
                    path,
                    rollingInterval: RollingInterval.Day,
                    retainedFileCountLimit: 14,
                    outputTemplate: OutputTemplate,
                    shared: true)
                .CreateLogger();

            Log.Logger = logger;
            return logger;
        }

        private static string DefaultLogDirectory()
        {
            return Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                "MarcusLaw",
                "OutlookAddin",
                "logs");
        }
    }
}
