using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Threading.Tasks;
using UnivateProperties_API.Context;
using UnivateProperties_API.Model.Communication;
using UnivateProperties_API.Model.Property;
using UnivateProperties_API.Model.Region;
using UnivateProperties_API.Model.Timeshare;
using UnivateProperties_API.Model.Users;
using UnivateProperties_API.Repository;
using UnivateProperties_API.Repository.Communication;
using UnivateProperties_API.Repository.Properties;
using UnivateProperties_API.Repository.Region;
using UnivateProperties_API.Repository.Timeshare;
using UnivateProperties_API.Repository.Users;

namespace UnivateProperties_API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();
            services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddDbContext<DataContext>(o => o.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            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 registerRepository = context.HttpContext.RequestServices.GetRequiredService<IRegisterRepository>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = registerRepository.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
                };
            });

            #region Property
            services.AddTransient<IRepository<Agent>, AgentRepository>();
            services.AddTransient<IRegisterRepository, RegisterRepository>();
            services.AddTransient<IRepository<Agency>, AgencyRepository>();
            services.AddTransient<IRepository<Email>, EmailRepository>();
            services.AddTransient<IRepository<SMTPAccount>, SMTPAccountRepository>();
            services.AddTransient<IRepository<SMTPHost>, SMTPHostRepository>();
            services.AddTransient<IPropertyRepository, PropertyRepository>();
            services.AddTransient<IPropertyImageRepository, PropertyImageRepository>();
            services.AddTransient<IRepository<PropertyType>, PropertyTypeRepository>();
            services.AddTransient<IRepository<PropertyUserField>, PropertyUserFieldRepository>();
            services.AddTransient<IRepository<UserDefinedField>, UserDefinedFieldRepository>();
            services.AddTransient<IUserDefinedGroupRepository, UserDefinedGroupRepository>();
            #endregion Property
            #region Region
            services.AddTransient<IRepository<Province>, ProvinceRepository>();
            services.AddTransient<ICityRepository, CityRepository>();
            services.AddTransient<ISuburbRepository, SuburbRepository>();
            #endregion Region
            #region Timeshare
            services.AddTransient<IRepository<Status>, StatusRepository>();
            services.AddTransient<IRepository<Season>, SeasonRepository>();
            services.AddTransient<IRepository<UnitConfiguration>, UnitConfigurationRepository>();
            services.AddTransient<IRepository<TimeshareWeek>, WeekRepository>();
            #endregion Timeshare
            #region User
            services.AddScoped<IRegisterRepository, RegisterRepository>();
            services.AddTransient<IRepository<Agent>, AgentRepository>();
            services.AddTransient<IRegisterRepository, RegisterRepository>();
            services.AddTransient<IRepository<Agency>, AgencyRepository>();
            services.AddTransient<IRepository<User>, UserRepository>();
            services.AddTransient<IRepository<Individual>, IndividualRepository>();
            #endregion User
            #region Communication
            services.AddTransient<IRepository<Email>, EmailRepository>();
            services.AddTransient<IRepository<SMTPAccount>, SMTPAccountRepository>();
            services.AddTransient<IRepository<SMTPHost>, SMTPHostRepository>();
            #endregion Communication
            services.Configure<MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}