using ExtensiblePortfolioSite.SDK.Plugins;

namespace ExtensiblePortfolioSite
{
    public class Program
    {
        private static void ParseArgs(String[] args, WebApplicationBuilder builder)
        {
            Boolean Error = false;
            Boolean Help = false;
            string ConfigPath = "eps_host_config.json";

            for (int x = 0; x < args.Length; x++)
            {
                String arg = args[x];
                if (arg[0] == '+')
                {
                    int s = arg.IndexOf('=');

                    String value = arg[(s + 1)..];

                    switch(arg[0..s])
                    {
                        case "+config":
                            ConfigPath = value;
                            break;

                        default:
                            Console.Error.WriteLine($"Unknown Arg '{arg}'");
                            Error = true;
                            break;
                    }
                }
                else if(arg == "help")
                    Help = true;
            }

            if(Help)
            {
                Console.Error.WriteLine(
@"
[Help Message]
+log_nofile                 Disable Flle Logging
+log_output={filepath}      Set Log File Output
+help                       Display Help Message
"
                );
                Environment.Exit(Error ? 0 : 2);
            }

            if(Error)
            {
                Console.Error.WriteLine("Exitting!");
                Environment.Exit(2);
            }

            Config.SetConfigFile(ConfigPath);
            LoggerProvider Logger;
            builder.Logging.ClearProviders();

            Config.ConfigObject Conf = Config.GetConfig();

            if (!Conf.LoggingSection.FileLogging)
                builder.Logging.AddProvider(Logger = new LoggerProvider(Conf.LoggingSection.ConsoleLogging));
            else
                builder.Logging.AddProvider(Logger = new LoggerProvider(Conf.LoggingSection.ConsoleLogging,
                    Conf.LoggingSection.FileLogPath!
                    .Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd"))
                    .Replace("{time}", DateTime.Now.ToString("HH.mm.ss"))
                    ));

            // Log On Error
            PluginManager.OnLogMessage += Logger.LogPluginManagerError;
        }

        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Load Config
            Config.GetConfig();

            // Parse input args
            ParseArgs(args, builder);

            // Load Plugins
            PluginManager.LoadPlugins(Path.GetFullPath("Plugins/"));

            //Initialize Plugins
            PluginManager.InitializePlugins();

            // TODO: [Resource] File Provider
            // TODO: [Plugin] Web Static Files Provider
            // TODO: [Plugin] Web Hook Provider
            // TODO: [Plugin] API Endpoint Provider
            // TODO: [Plugin] Reloading/Updating/Disabling

            // Add services to the container.
            builder.Services.AddRazorPages();

            // Add Responce Cache
            builder.Services.AddResponseCaching();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection(); // not required but, prefered

            app.UseStaticFiles("/content");

            app.UseRouting();

            app.UseResponseCaching();

            //app.UseAuthorization(); // not needed

            app.MapRazorPages();

            app.Run();
        }
    }
}