using Microsoft.Extensions.Logging;
using WorkFlowCheck.MAUI.Services;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.DependencyInjection;
using CommunityToolkit.Maui;
using WorkFlowCheck.MAUI.DataLayer;
using WorkFlowCheck.MAUI.Mapper;
using WorkFlowCheck.MAUI.Services.Interfaces;
using DevExpress.Maui;
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Hosting;
using CommunityToolkit.Maui.Core;
using WorkFlowCheck.MAUI.Handlers;
using WorkFlowCheck.MAUI.Helper;
using Plugin.Firebase.CloudMessaging;
using Microsoft.Maui.LifecycleEvents;

#if ANDROID
using Plugin.Firebase.Core.Platforms.Android;
#endif
namespace WorkFlowCheck.MAUI
{
    public static class MauiProgram
    {
        public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder.UseDevExpress(useLocalization: false)
                   .UseDevExpressControls()
                   .UseDevExpressCollectionView();

            builder.Services.AddAutoMapper(typeof(MapperProfile));
            builder.Services.AddHttpClient();
            builder.Services.AddDbContext<AppDbContext>();


            builder.Services.AddSingleton<IUserService, UserService>();
            builder.Services.AddSingleton<ISyncService, SyncService>();
            builder.Services.AddSingleton<IBaseStockService, BaseStockService>();
            builder.Services.AddSingleton<ICheckListService, CheckListService>();

            builder.Services.AddTransient<MainPage>();

            builder
                .UseMauiApp<App>()
                .UseDevExpressEditors()
                .UseMauiCommunityToolkitCamera()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                    fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                    fonts.AddFont("FontAwesome.ttf", "FontAwesome");
                })
                .RegisterFirebaseServices()
                .UseMauiCommunityToolkitCore()
                .UseMauiCommunityToolkit();
#if DEBUG
            builder.Logging.AddDebug();
#endif

            var app = builder.Build();

            using (var scope = app.Services.CreateScope())
            {
                Task.Run(async () =>
                {
                    await SystemHelper.GetAPIInfoAsync();
                }).GetAwaiter().GetResult();
            }

            ServiceProvider = app.Services;
            return app;
        }

        public static IServiceProvider ServiceProvider { get; private set; }



        private static MauiAppBuilder RegisterFirebaseServices(this MauiAppBuilder builder)
        {
            builder.ConfigureLifecycleEvents(events =>
            {
#if ANDROID
                events.AddAndroid(android => android.OnCreate((activity, _) =>
                CrossFirebase.Initialize(activity)));
#endif
            });
            return builder;
        }
    }
}