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

namespace NetworkResurrector.Agent
{
    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()
                .Enrich.With(new AgentCodeEventEnricher(builder.Configuration))
                .WriteTo.Console()
                .WriteTo.ConfiguredDestinations(builder.Configuration);
            });

            builder.Services.ConfigureServices(builder.Configuration);

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

            var exitCode = 0;
            try
            {
                var urls = builder.Configuration.GetValue<string>("Urls");
                var agentCode = builder.Configuration.GetValue<string>("Agent:Code");

                Log.Information($"Starting network resurrector agent {agentCode}...");
                Log.Information($"Network resurrector agent {agentCode} listening on {urls}");
                Log.Information($"Hostname: {Environment.MachineName}");
                Console.WriteLine("Application started. Press Ctrl+C to shut down.");
                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Network resurrector agent host terminated unexpectedly");
                exitCode = 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
            Environment.Exit(exitCode);
        }
    }
}
