using System;
using System.IO;
using System.Reflection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using Serilog;

namespace OnlineAssessment
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.File(LogFilePath,
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
                    rollingInterval: RollingInterval.Day)
                .CreateLogger();

            try
            {
                Log.Information("--------------------------APPLICATION STARTED---------------------");

                CreateHostBuilder(args)
                    .Build()
                    .Run();

                Log.Information("--------------------------APPLICATION STOPPED---------------------");
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

        static string LogFilePath
        {
            get
            {
                var basePath = string.Concat(PlatformServices.Default.Application.ApplicationBasePath, "Logs");
                var fileName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name + "-Log-.txt";
                return Path.Combine(basePath, fileName);
            }
        }
    }
}
