using CommunityToolkit.Maui;
using CommunityToolkit.Maui.Markup;
using Microsoft.Extensions.Logging;
using RBLNews.Shared.Services;

namespace RBLNews.Maui
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .UseMauiCommunityToolkit()
                .UseMauiCommunityToolkitMarkup()
                .ConfigureFonts(fonts =>
                {
                    //fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("NanumMyeongjo-Regular.ttf", "NanumMyeongjoRegular");
                });

            builder.Services.AddMauiBlazorWebView();
            builder.Services.AddBlazorBootstrap();

            builder.Services.AddSingleton<IFeedDataService, FeedDataService>();
            builder.Services.AddSingleton<AppLifecycleService>();

#if DEBUG
    		builder.Services.AddBlazorWebViewDeveloperTools();
            builder.Logging.AddDebug();
#endif
            
            MauiApp app = builder.Build();

            using var serviceScope = app.Services.CreateScope();
            var services = serviceScope.ServiceProvider;

            var environmentVariablesService = services.GetRequiredService<EnvironmentVariablesService>();
            string? backendApiUrl = environmentVariablesService.RblApiUrl;

            if (string.IsNullOrEmpty(backendApiUrl))
            {
                throw new Exception($"can't instantiate services, due to paramters are null. backendApiUrl: '{backendApiUrl}'");
            }

            return app;
        }
    }
}
