using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WebApplication1.Models;

namespace WebApplication1
{
    public class EmailService : IIdentityMessageService
    {
        private readonly string _host;
        private readonly int _port;
        private readonly string _username;
        private readonly string _password;
        private readonly bool _enableSsl;
        private readonly string _from;
        private readonly string _fromDisplay;

        public EmailService()
        {
            _host = ConfigurationManager.AppSettings["Smtp:Host"] ?? Environment.GetEnvironmentVariable("SMTP_HOST");
            _port = ParseInt(ConfigurationManager.AppSettings["Smtp:Port"])
                    ?? ParseInt(Environment.GetEnvironmentVariable("SMTP_PORT")) ?? 587;
            _username = ConfigurationManager.AppSettings["Smtp:Username"] ?? Environment.GetEnvironmentVariable("SMTP_USER");
            _password = ConfigurationManager.AppSettings["Smtp:Password"] ?? Environment.GetEnvironmentVariable("SMTP_PASS");
            _enableSsl = ParseBool(ConfigurationManager.AppSettings["Smtp:EnableSsl"])
                         ?? ParseBool(Environment.GetEnvironmentVariable("SMTP_ENABLESSL")) ?? true;
            _from = ConfigurationManager.AppSettings["Email:From"] ?? _username ?? Environment.GetEnvironmentVariable("EMAIL_FROM");
            _fromDisplay = ConfigurationManager.AppSettings["Email:FromDisplayName"] ?? "Најди Ментор";
        }

        private int? ParseInt(string s) => int.TryParse(s, out var v) ? (int?)v : null;
        private bool? ParseBool(string s) => bool.TryParse(s, out var v) ? (bool?)v : null;

        // Called by ASP.NET Identity when it needs to send e-mail (confirmations, password reset, etc.)
        public async Task SendAsync(IdentityMessage message)
        {
            if (message == null) throw new ArgumentNullException(nameof(message));
            await SendEmailAsync(message.Destination, message.Subject, message.Body, null).ConfigureAwait(false);
        }

        public async Task SendEmailAsync(string toEmail, string subject, string htmlBody, string plainBody = null)
        {
            if (string.IsNullOrWhiteSpace(_host))
                throw new InvalidOperationException("SMTP host is not configured (Smtp:Host).");

            if (string.IsNullOrWhiteSpace(toEmail))
                throw new ArgumentException("toEmail required", nameof(toEmail));

            var mail = new MailMessage
            {
                From = new MailAddress(_from ?? _username, _fromDisplay),
                Subject = subject ?? string.Empty,
                BodyEncoding = Encoding.UTF8,
                SubjectEncoding = Encoding.UTF8,
                IsBodyHtml = true,
                Body = htmlBody ?? string.Empty
            };

            if (!string.IsNullOrEmpty(plainBody))
                mail.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainBody, null, "text/plain"));

            mail.To.Add(toEmail);

            using (var client = new SmtpClient(_host, _port))
            {
                client.EnableSsl = _enableSsl;
                if (!string.IsNullOrEmpty(_username))
                    client.Credentials = new NetworkCredential(_username, _password);

                await client.SendMailAsync(mail).ConfigureAwait(false);
            }
        }
    }

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }

    // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
        }

        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
        {
            var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 6,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault = true;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
            {
                Subject = "Security Code",
                BodyFormat = "Your security code is {0}"
            });
            manager.EmailService = new EmailService();
            manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider = 
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    // Configure the application sign-in manager which is used in this application.
    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    {
        public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
        {
            return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
        }

        public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
        {
            return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
        }
    }
}
