using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
using System.IO;
using VitrosConsole.FolderWatcher;
using VitrosConsole.Parser;
using VitrosConsole.Persistence;
using VitrosConsole.Port;

namespace VitrosConsole
{
    class Program
    {
        static IConfiguration configuration;
        static ILogger logger;
        static void Main(string[] args)
        {
            try
            {
                var builder = new ConfigurationBuilder();
                BuildConfiguration(builder);
                configuration = builder.Build();

                var services = new ServiceCollection();
                ConfigureServices(services);

                ServiceProvider serviceProvider = services.BuildServiceProvider();

                logger = serviceProvider.GetService<ILogger<Program>>();

                var app = serviceProvider.GetService<Application>();

                try
                {
                    app.Start();
                    logger.LogInformation("Press \'q\' to quit the application.");
                    while (Console.Read() != 'q') ;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "Failure during Application run");
                    app.Start();
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Failure during Application Initialization");
            }
        }

        private static void BuildConfiguration(IConfigurationBuilder builder)
        {
            builder.SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile("appsettings.json", false, true);
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(configuration)
                    .AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")))
                    .Configure<SerialPortConfig>(configuration.GetSection("SerialPort"))
                    .AddTransient<FolderWatcherService>()
                    .AddTransient<VitrosParser>()
                    .AddTransient<PersistenceService>()
                    .AddTransient<Application>()
                    .AddTransient<SerialPortListener>();

            services.AddLogging(options =>
            {
                //options.SetMinimumLevel(LogLevel.Information);
                options.AddConfiguration(configuration.GetSection("Logging"));
                options.AddConsole();
                options.AddNLog("nlog.config");
            });
        }
    }
}
