using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using NetworkResurrector.Server.Extensions;
using Serilog;
using System;
using System.Diagnostics;
using System.Linq;

namespace NetworkResurrector.Server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var isConsole = Debugger.IsAttached || args.Contains("--console");

            WebApplicationBuilder builder;
            if (isConsole)
            {
                builder = WebApplication.CreateBuilder(args);
            }
            else
            {
                var webApplicationOptions = new WebApplicationOptions()
                {
                    ContentRootPath = AppContext.BaseDirectory,
                    Args = args,
                    ApplicationName = Process.GetCurrentProcess().ProcessName
                };
                builder = WebApplication.CreateBuilder(webApplicationOptions);
                builder.Host.UseWindowsService();
            }

            builder.Host.UseSerilog((_, lc) =>
            {
                lc
                .ReadFrom.Configuration(builder.Configuration)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.ConfiguredDestinations(builder.Configuration);
            });

            builder.Services.ConfigureServices(builder.Configuration);
            var app = builder.Build();
            app.Configure();

            var exitCode = 0;

            try
            {
                var urls = builder.Configuration.GetValue<string>("Urls");
                Log.Information("Starting network resurrector server...");
                Log.Information($"Server listening on {urls}");
                Console.WriteLine("Application started. Press Ctrl+C to shut down.");
                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Network resurrector server host terminated unexpectedly");
                exitCode = 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }

            Environment.Exit(exitCode);
        }
    }
}
