using MassTransit;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
// using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text;
using System.Threading.Tasks;
using WK_KLI_LAPS_Service.App_Data;
using WK_KLI_LAPS_Service.Controllers.CheckListDetails;
using WK_KLI_LAPS_Service.Controllers.Common.SendMail;
using WK_KLI_LAPS_Service.Controllers.Common.Uploader;
using WK_KLI_LAPS_Service.Controllers.Configuration.Job;
using WK_KLI_LAPS_Service.Controllers.Configuration.Job.AutoArchiveJob;
using WK_KLI_LAPS_Service.Controllers.Configuration.Outline;
using WK_KLI_LAPS_Service.Controllers.Configuration.Outline.Outline;
using WK_KLI_LAPS_Service.Controllers.Configuration.Outline.OutlineStageMapping;
using WK_KLI_LAPS_Service.Controllers.Configuration.Project;
using WK_KLI_LAPS_Service.Controllers.Configuration.SmartChart;
using WK_KLI_LAPS_Service.Controllers.Configuration.UserManagement.ProjectMapping;
using WK_KLI_LAPS_Service.Controllers.Configuration.UserManagement.RoleMapping;
using WK_KLI_LAPS_Service.Controllers.Configuration.WorkFlow;
using WK_KLI_LAPS_Service.Controllers.Dashboard;
using WK_KLI_LAPS_Service.Controllers.Master.AllocationType;
using WK_KLI_LAPS_Service.Controllers.Master.Application;
using WK_KLI_LAPS_Service.Controllers.Master.AppUrl;
using WK_KLI_LAPS_Service.Controllers.Master.ChapterType;
using WK_KLI_LAPS_Service.Controllers.Master.CheckList;
using WK_KLI_LAPS_Service.Controllers.Master.Customer;
using WK_KLI_LAPS_Service.Controllers.Master.CustomerContact;
using WK_KLI_LAPS_Service.Controllers.Master.Department;
using WK_KLI_LAPS_Service.Controllers.Master.Feature;
using WK_KLI_LAPS_Service.Controllers.Master.FileMode;
using WK_KLI_LAPS_Service.Controllers.Master.FileType;
using WK_KLI_LAPS_Service.Controllers.Master.Frequency;
using WK_KLI_LAPS_Service.Controllers.Master.HeadingLevel;
using WK_KLI_LAPS_Service.Controllers.Master.JobMeta;
using WK_KLI_LAPS_Service.Controllers.Master.Lot;
using WK_KLI_LAPS_Service.Controllers.Master.LotBatch;
using WK_KLI_LAPS_Service.Controllers.Master.MailField;
using WK_KLI_LAPS_Service.Controllers.Master.MailTemplate;
using WK_KLI_LAPS_Service.Controllers.Master.Menu;
using WK_KLI_LAPS_Service.Controllers.Master.Metadata;
using WK_KLI_LAPS_Service.Controllers.Master.MipTopic1;
using WK_KLI_LAPS_Service.Controllers.Master.MipTopic2;
using WK_KLI_LAPS_Service.Controllers.Master.MipTopic3;
using WK_KLI_LAPS_Service.Controllers.Master.Plugin;
using WK_KLI_LAPS_Service.Controllers.Master.PrintSupplement;
using WK_KLI_LAPS_Service.Controllers.Master.ProductionWorkFlow;
using WK_KLI_LAPS_Service.Controllers.Master.Project;
using WK_KLI_LAPS_Service.Controllers.Master.Role;
using WK_KLI_LAPS_Service.Controllers.Master.Server;
using WK_KLI_LAPS_Service.Controllers.Master.Skill;
using WK_KLI_LAPS_Service.Controllers.Master.Stage;
using WK_KLI_LAPS_Service.Controllers.Master.StageType;
using WK_KLI_LAPS_Service.Controllers.Master.StateCode;
using WK_KLI_LAPS_Service.Controllers.Master.SubSkill;
using WK_KLI_LAPS_Service.Controllers.Master.SupplementType;
using WK_KLI_LAPS_Service.Controllers.Master.Toolset;
using WK_KLI_LAPS_Service.Controllers.Master.Track;
using WK_KLI_LAPS_Service.Controllers.Master.Unit;
using WK_KLI_LAPS_Service.Controllers.Master.User;
using WK_KLI_LAPS_Service.Controllers.Master.Vendor;
using WK_KLI_LAPS_Service.Controllers.Master.WorkFlow;
using WK_KLI_LAPS_Service.Controllers.Master.Error;
using WK_KLI_LAPS_Service.Controllers.NavMenu;
using WK_KLI_LAPS_Service.Controllers.ReleaseNotes;
using WK_KLI_LAPS_Service.Controllers.Reports;
using WK_KLI_LAPS_Service.Controllers.UserManagement.EmailMapping;
using WK_KLI_LAPS_Service.Controllers.UserManagement.StageMapping;
using WK_KLI_LAPS_Service.Controllers.WorkArea;
using WK_KLI_LAPS_Service.Hub;
using WK_KLI_LAPS_Service.Models;
using WK_KLI_LAPS_Service.Controllers.Master.ErrorRemarks;
using WK_KLI_LAPS_Service.Controllers.Master.LobDetails;
using WK_KLI_LAPS_Service.Controllers.Master.Lob;
using WK_KLI_LAPS_Service.Controllers.Master.Chartvalue;

namespace WK_KLI_LAPS_Service
{
    public class Startup
    {

        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                  .SetBasePath(env.ContentRootPath)
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            Configuration = builder.Build();
            //Configuration = configuration;
        }

        static public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.

        public void ConfigureServices(IServiceCollection services)
        {
            // services.AddRazorPages();
            //  services.AddCors();
            services.AddControllers();

            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy",
            //        builder => builder.AllowAnyOrigin()
            //        .AllowAnyMethod()
            //        .AllowAnyHeader());
            //});
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy", builder =>
                    builder.SetIsOriginAllowed(_ => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });

            // services.AddControllers();
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy",
            //        builder => builder.WithOrigins("http://localhost:4200", "www.google.com")
            //        .AllowAnyMethod()
            //        .AllowAnyHeader()
            //        .AllowCredentials());
            //});
            services.AddSignalR();
            // services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);
            // services.AddSingleton<RabbitMQClient, RabbitMQClient>();
            string ServiceAddress = "";
            string RabbitMQHost = "";
            string userName = "";
            string password = "";

            ServiceAddress = Startup.Configuration.GetValue<string>("AppSettings:chechoutqueue_path") + "" + "/" + Startup.Configuration.GetValue<string>("AppSettings:chechoutqueue");
            RabbitMQHost = Startup.Configuration.GetValue<string>("AppSettings:chechoutqueue_path");
            userName = "admin";
            password = "admin";

            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri(RabbitMQHost), h =>
                {
                    h.Username(userName);
                    h.Password(password);
                });
            });

            services.AddSingleton<IPublishEndpoint>(bus);
            services.AddSingleton<ISendEndpointProvider>(bus);
            services.AddSingleton<IBus>(bus);
            // services.AddHostedService<MessageQueueService>();
            var timeout = TimeSpan.FromSeconds(10);
            var serviceAddress = new Uri(ServiceAddress);

            services.AddScoped<IRequestClient<ISimpleRequest, ISimpleResponse>>(x =>
                new MessageRequestClient<ISimpleRequest, ISimpleResponse>(x.GetRequiredService<IBus>(), serviceAddress, timeout, timeout));

            bus.Start();


            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<Appsettings>(appSettingsSection);



            // configure jwt authentication
            var appSettings = appSettingsSection.Get<Appsettings>();

            //hangfire

            //services.AddHangfire(config =>
            //     config.UsePostgreSqlStorage(appSettings.ConnectionStringSchedule));

            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            services.AddHttpContextAccessor();
            //// configure DI for application services
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IStageService, StageService>();
            services.AddScoped<IStageTypeService, StageTypeService>();
            services.AddScoped<IRoleService, RoleService>();
            services.AddScoped<IMenuService, MenuService>();
            services.AddScoped<IServerService, ServerService>();
            services.AddScoped<IApplicationService, ApplicationService>();
            services.AddScoped<ICheckListService, CheckListService>();
            services.AddScoped<IDepartmentService, DepartmentService>();
            services.AddScoped<IWorkFlowService, WorkFlowService>();
            services.AddScoped<INavMenuService, NavMenuService>();
            services.AddScoped<IMailTemplateService, MailTemplateService>();
            services.AddScoped<IMailFieldService, MailFieldService>();
            services.AddScoped<ISendMailService, SendMailService>();
            services.AddScoped<IUnitService, UnitService>();
            services.AddScoped<IFileTypeService, FileTypeService>();
            services.AddScoped<IAllocationTypeService, AllocationTypeService>();
            services.AddScoped<IFileModeService, FileModeService>();
            services.AddScoped<IWorkFlowConfigurationService, WorkFlowConfigurationService>();
            services.AddScoped<IJobConfigurationService, JobConfigurationService>();
            services.AddScoped<ICustomerService, CustomerService>();
            services.AddScoped<ICustomerContactService, CustomerContactService>();
            services.AddScoped<ICheckListDetailsService, CheckListDetailsService>();
            services.AddScoped<IProjectService, ProjectService>();
            services.AddScoped<IProjectConfigurationService, ProjectConfigurationService>();
            services.AddScoped<ISkillService, SkillService>();
            services.AddScoped<ISubSkillService, SubSkillService>();
            services.AddScoped<IUserProjectMappingService, UserProjectMappingService>();
            services.AddScoped<IUserRoleMappingService, UserRoleMappingService>();
            services.AddScoped<IVendorService, VendorService>();
            services.AddScoped<IStageMappingService, StageMappingService>();
            services.AddScoped<IMetadataService, MetadataService>();
            services.AddScoped<IChapterTypeService, ChapterTypeService>();
            services.AddScoped<ILotService, LotService>();
            services.AddScoped<IWorkAreaService, WorkAreaService>();
            services.AddScoped<IUploaderService, UploaderService>();
            services.AddScoped<IUserMailMappingService, UserMailMappingService>();
            services.AddScoped<ITrackService, TrackService>();
            services.AddScoped<IOutlineConfigurationService, OutlineConfigurationService>();
            services.AddScoped<IOutlineService, OutlineService>();
            services.AddScoped<IHeadingLevelService, HeadingLevelService>();
            services.AddScoped<IPluginService, PluginService>();
            services.AddScoped<IToolsetService, ToolsetService>();
            services.AddScoped<ISmartChartService, SmartChartService>();
            services.AddScoped<IOutlineStageMappingService, OutlineStageMappingService>();
            services.AddScoped<IFeatureService, FeatureService>();
            services.AddScoped<IReleaseNotesService, ReleaseNotesServices>();
            services.AddScoped<IDashboardService, DashboardService>();
            services.AddScoped<IAuthorDashboardService, AuthorDashboardService>();
            services.AddScoped<ILotBatchService, LotBatchService>();
            services.AddScoped<IMipTopic1Service, MipTopic1Service>();
            services.AddScoped<IMipTopic2Service, MipTopic2Service>();
            services.AddScoped<IMipTopic3Service, MipTopic3Service>();
            services.AddScoped<IAppUrlService, AppUrlService>();
            services.AddScoped<IProductionWorkFlowService, ProductionWorkflowService>();
            services.AddScoped<ISupplementTypeService, SupplementTypeService>();
			services.AddScoped<IJobMetaService, JobMetaService>();
            services.AddScoped<IPrintSupplementService, PrintSupplementService>();
            services.AddScoped<ITopBarMenu, TopBarMenuService>();
            services.AddScoped<IStateCodeService, StatecodeService>();
            services.AddScoped<IFrequencyService, FrequencyService>();
            services.AddScoped<ICategoryService, CategoryService>();
            services.AddScoped<IAutoArchiveJobService, AutoArchiveJobService>();
            services.AddScoped<IErrorService, ErrorService>();
            services.AddScoped<IErrorremarksService, ErrorremarksService>();
            services.AddScoped<ILobDetailsService, LobDetailsService>();
            services.AddScoped<ILobService, LobService>();
			services.AddScoped<IChartValuesService, ChartValuesService>();
            // services.AddRabbit(Configuration);

            //  services.AddMvc(option => option.EnableEndpointRouting = false);
            // services.AddMvc(option => option.EnableEndpointRouting = false);

            //services.Configure<MvcOptions>(options =>
            //{
            //    options.Filters.Add(new CorsAuthorizationFilterFactory("AllowMyOrigin"));
            //});


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    // 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();
            //app.UseMvc();
            //app.Use(async (ctx, next) =>
            //{
            //    await next();
            //    if (ctx.Response.StatusCode == 204)
            //    {
            //        ctx.Response.ContentLength = 0;
            //    }
            //});

            app.UseSignalR(routes =>
            {
                routes.MapHub<AuthHub>("/authhub");
            });
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //    app.UseHsts();
            //}
            WK_KLI_LAPS_Service.App_Data.AppContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
            app.UseAuthentication();

            app.UseHttpsRedirection();
            // app.UseMvc();
            app.UseRouting();
            app.UseCors("CorsPolicy");

            app.UseAuthorization();
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
