//using AyCode.Core.Loggers;

using AyCode.Core.Loggers;
using DevExpress.AspNetCore;
using FruitBank.Common;
using FruitBank.Common.Interfaces;
using FruitBank.Common.Server.Interfaces;
using FruitBank.Common.Server.Services.Loggers;
using FruitBank.Common.Server.Services.SignalRs;
using Mango.Nop.Services;
using Mango.Nop.Services.Loggers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Nop.Core.Domain.Orders;
using Nop.Core.Infrastructure;
using Nop.Data;
using Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers;
using Nop.Plugin.Misc.FruitBankPlugin.Controllers;
using Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;
using Nop.Plugin.Misc.FruitBankPlugin.Factories;
using Nop.Plugin.Misc.FruitBankPlugin.Filters;
using Nop.Plugin.Misc.FruitBankPlugin.Models;
using Nop.Plugin.Misc.FruitBankPlugin.Services;
using Nop.Plugin.Misc.FruitBankPlugin.Services.FileStorage;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Events;
using Nop.Services.Messages;
using Nop.Web.Areas.Admin.Factories;
using Nop.Web.Areas.Admin.Models.Catalog;
using Nop.Web.Areas.Admin.Models.Orders;
using System.Net.Http.Headers;

namespace Nop.Plugin.Misc.FruitBankPlugin.Infrastructure;

public class PluginNopStartup : INopStartup
{
    /// <summary>
    /// Add and configure any of the middleware
    /// </summary>
    /// <param name="services">Collection of service descriptors</param>
    /// <param name="configuration">Configuration of the application</param>
    public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<IAcLogWriterBase, ConsoleLogWriter>();

        services.AddTransient<INopLoggerMsSqlNopDataProvider, NopLoggerMsSqlNopDataProvider>();
        services.AddScoped<IAcLogWriterBase, NopLogWriter>();

        services.AddSingleton<LoggerToLoggerApiController>();
        //services.AddSingleton<SessionService>();

        services.Configure<RazorViewEngineOptions>(options =>
        {
            options.ViewLocationExpanders.Add(new ViewLocationExpander());
        });

        services.AddSingleton<ILockService, LockService>();
        services.AddScoped<FruitBankAttributeService>();

        services.AddScoped<ProductDtoDbTable>();
        services.AddScoped<OrderDtoDbTable>();
        services.AddScoped<OrderItemDtoDbTable>();
        services.AddScoped<OrderItemPalletDbTable>();

        services.AddScoped<PartnerDbTable>();
        services.AddScoped<ShippingDbTable>();
        services.AddScoped<ShippingDocumentDbTable>();
        services.AddScoped<ShippingItemDbTable>();
        services.AddScoped<ShippingItemPalletDbTable>();
        services.AddScoped<FilesDbTable>();
        services.AddScoped<ShippingDocumentToFilesDbTable>();

        services.AddScoped<StockQuantityHistoryDtoDbTable>();

        services.AddScoped<StockTakingDbTable>();
        services.AddScoped<StockTakingItemDbTable>();
        services.AddScoped<StockTakingItemPalletDbTable>();

        services.AddScoped<StockTakingDbContext>();
        services.AddScoped<FruitBankDbContext>();

        services.AddScoped<SignalRSendToClientService>();
        services.AddScoped<IFruitBankDataControllerServer, FruitBankDataController>();
        services.AddScoped<ICustomOrderSignalREndpointServer, CustomOrderSignalREndpoint>();
        services.AddScoped<IStockSignalREndpointServer, StockSignalREndpointServer>();

        //services.AddScoped<CustomModelFactory, ICustomerModelFactory>();
        services.AddScoped<IPriceCalculationService, CustomPriceCalculationService>();
        services.AddScoped<PriceCalculationService, CustomPriceCalculationService>();
        services.AddScoped<IConsumer<OrderPlacedEvent>, EventConsumer>();
        services.AddScoped<IOrderMeasurementService, OrderMeasurementService>();
        services.AddScoped<PendingMeasurementCheckoutFilter>();
        services.AddScoped<InnVoiceApiService>();
        services.AddScoped<InnVoiceOrderService>();

        services.AddScoped<MeasurementService>();
        services.AddScoped<ReplicateService>();

        services.AddHttpClient<ReplicateService>(client =>
        {
            client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", "r8_MUApXYIE5mRjxqy20tsGLehWBJkCzNj0Cwvrh");
        });

        //services.AddScoped<OrderListModel, OrderListModelExtended>();
        //services.AddScoped<OrderModel, OrderModelExtended>();
        //services.AddScoped<OrderSearchModel, OrderSearchModelExtended>();

        services.AddScoped<IOrderModelFactory, CustomOrderModelFactory>();
        services.AddScoped<IProductModelFactory, CustomProductModelFactory>();
        services.AddScoped<IGenericAttributeService, GenericAttributeService>();
        services.AddScoped<CerebrasAPIService>();
        services.AddScoped<OpenAIApiService>();
        //services.AddScoped<IAIAPIService, OpenAIApiService>();
        services.AddScoped<AICalculationService>();
        services.AddScoped<PdfToImageService>();
        services.AddScoped<IWorkflowMessageService, WorkflowMessageService>();

        services.AddSingleton<IFileStorageProvider>(sp =>
            new LocalFileStorageProvider() // Uses default wwwroot/uploads
                                           // Or specify custom path:
                                           // new LocalFileStorageProvider(Path.Combine(Directory.GetCurrentDirectory(), "MyCustomPath"))
        );

        // Register the file storage service
        services.AddScoped<FileStorageService>();

        services.AddControllersWithViews(options =>
        {
            options.Filters.AddService<PendingMeasurementCheckoutFilter>();
        });

        services.AddSignalR(hubOptions =>
        {
            hubOptions.EnableDetailedErrors = true;
            hubOptions.MaximumReceiveMessageSize = 30_000_000; // 256 * 1024; unlimited: null;
            hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(FruitBankConstClient.SignalRKeepAliveIntervalSecond);
            hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(FruitBankConstClient.SignarlRTimeoutIntervalSecond);

            //hubOptions.MaximumParallelInvocationsPerClient = 1; //default: 1;
            hubOptions.StatefulReconnectBufferSize = 30_000_000; //30MB; //default: 100,000 bytes;
            //hubOptions.HandshakeTimeout = TimeSpan.FromSeconds(15); //default timeout is 15 seconds
        });
    }

    /// <summary>
    /// Configure the using of added middleware
    /// </summary>
    /// <param name="application">Builder for configuring an application's request pipeline</param>
    public void Configure(IApplicationBuilder application)
    {
        var fruitBankHubEndPoint = $"/{FruitBankConstClient.DefaultHubName}";
        application.UseWhen(context => context.Request.Path.StartsWithSegments(fruitBankHubEndPoint), app =>
        {
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<DevAdminSignalRHub>(fruitBankHubEndPoint, options =>
                {
                    options.Transports = HttpTransportType.WebSockets;// | HttpTransportType.LongPolling;
                    options.WebSockets.CloseTimeout = TimeSpan.FromSeconds(10); //default: 5 sec.
                    //options.LongPolling.PollTimeout = new TimeSpan(0, 0, 90); //default: 90 sec.

                    options.AllowStatefulReconnects = true;
                    options.TransportMaxBufferSize = 30_000_000; // Increasing this value allows the server to receive larger messages. default: 65KB; unlimited: 0;
                    options.ApplicationMaxBufferSize = 30_000_000; //Increasing this value allows the server to send larger messages. default: 65KB; unlimited: 0;

                    options.TransportSendTimeout = TimeSpan.FromSeconds(60); //default: 10 sec.
                });
            });
        });

        var loggrHubEndPoint = $"/{FruitBankConstClient.LoggerHubName}";
        application.UseWhen(context => context.Request.Path.StartsWithSegments(loggrHubEndPoint), app =>
        {
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<LoggerSignalRHub>(loggrHubEndPoint, options =>
                {
                    options.Transports = HttpTransportType.WebSockets;
                    options.AllowStatefulReconnects = false;
                });
            });
        });
    }

    /// <summary>
    /// Gets order of this startup configuration implementation
    /// </summary>
    public int Order => 4000;
}