using Azure.Extensions.AspNetCore.Configuration.Secrets;
using Azure.Identity;
using System;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

namespace SyncfusionSchedulerDeleteBug.Blazor.Server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                if (context.HostingEnvironment.IsProduction())
                {
                    Console.WriteLine("Starting certificate load");

                    var builtConfig = config.Build();

                    try
                    {
                        using (var store = new X509Store(StoreLocation.LocalMachine))
                        {
                            store.Open(OpenFlags.ReadOnly);
                            var certs = store.Certificates
                                .Find(X509FindType.FindByThumbprint,
                                    builtConfig["AzureADCertThumbprint"], false);

                            Console.WriteLine($"Store count: {store.Certificates.Count}");
                            Console.WriteLine($"Certificate count: {certs.Count}");

                            if (certs.Count > 0)
                                Console.WriteLine($"Certificate {certs[0].Thumbprint}");

                            var uri = new Uri($"https://{builtConfig["KeyVaultName"]}.vault.azure.net/");
                            Console.WriteLine(uri.AbsoluteUri);

                            var tenant = builtConfig["AzureADDirectoryId"];
                            Console.WriteLine(tenant);

                            var appId = builtConfig["AzureADApplicationId"];
                            Console.WriteLine(appId);

                            config.AddAzureKeyVault(uri, new ClientCertificateCredential(tenant, appId, certs.OfType<X509Certificate2>().Single()), new KeyVaultSecretManager());

                            store.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception occured");
                    }
                    finally
                    {
                        Console.WriteLine("Certificate load complete");
                    }
                }
            })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });        


    }
}
