using System;
using System.IO;
using Serilog;
using Serilog.Formatting.Json;
using SharpRss;
using ToolQit;
using ToolQit.Containers;
using ToolQit.Logging;
using ToolQit.Logging.Serilog;

namespace WebSharpRSS
{
    public static class Bootstrapper
    {
        private static bool _defaultsSet;
        private static bool _bootstrapped;
        private static readonly ILog Log = LogManager.CreateLogger(typeof(Bootstrapper));

        public static void Bootstrap()
        {
            if (_bootstrapped) return;
            Caretaker.Settings.SetAppDefaultSettings();
            SetupLogging();
            Log.Information("Starting SharpRSS...");
            SyndicationManager.Init();
            _bootstrapped = true;
        }

        private static void SetAppDefaultSettings(this DataContainer dataCon)
        {
            var paths = dataCon["Paths"];
            //paths.Set("FaviconResolveUrl", "https://icons.duckduckgo.com/ip3/{0}.ico", false);
            paths.Set("FaviconResolveUrl", "http://www.google.com/s2/favicons?domain={0}", false);
            paths.Set("LogPath", Path.Combine(Environment.CurrentDirectory, "logs", "log_.json"), false);
            _defaultsSet = true;
        }

        private static LoggerConfiguration? _configuration;
        private static void SetupLogging()
        {
            if (!_defaultsSet) throw new Exception("Bootstrapper defaults are not initialized!");
            if (_configuration != null) return;
            _configuration = new LoggerConfiguration()
                .Enrich.With(new LogEnricher())
                .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} - {Sender} | {Level:u3}] {Message:lj}{NewLine}{Exception}")
                .WriteTo.File(new JsonFormatter(), Caretaker.Settings["Paths"].GetString("LogPath"),
                    rollingInterval: RollingInterval.Day);
                /*.MinimumLevel.Verbose(); // ONLY FOR DEBUGGING!!!*/
            
            Serilog.Log.Logger = _configuration.CreateLogger();
            LogManager.RegisterAdapter(new SerilogAdapter(Serilog.Log.Logger));
        }
    }
}