using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using PowerAccounting.Areas.Identity.Data;
using PowerAccounting.Models2;
using PowerAccounting.MyModels;
//using PowerAccounting.TempModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Webgentle.BookStore.Models;


namespace Webgentle.BookStore.Repository
{
    public class AccountRepository : IAccountRepository
    {
        private readonly UserManager<PowerAccountingUser> _userManager;
        private readonly SignInManager<PowerAccountingUser> _signInManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        private readonly IConfiguration _configuration;
        private readonly db_a63a88_iprotechContext db;
        public AccountRepository(UserManager<PowerAccountingUser> userManager,
            SignInManager<PowerAccountingUser> signInManager,
            RoleManager<IdentityRole> roleManager,
            IConfiguration configuration, db_a63a88_iprotechContext _db)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _roleManager = roleManager;
            _configuration = configuration;
            db = _db;
        }

       
    
        public async Task<List<IdentityResult>> SetingsRoles()
        {     
            List<IdentityResult> allTest = new List<IdentityResult>();
            var testRoleAdmin = await _roleManager.RoleExistsAsync("Admin");
            if (!testRoleAdmin)
            {
                IdentityRole role = new IdentityRole() { Name = "Admin" };
               allTest.Add( await _roleManager.CreateAsync(role));
            }
            var testRoleManager = await _roleManager.RoleExistsAsync("Manager");
            if (!testRoleManager)
            {
                IdentityRole role = new IdentityRole() { Name = "Manager" };
                allTest.Add(await _roleManager.CreateAsync(role));
            }
            var testRoleEmployee = await _roleManager.RoleExistsAsync("Employee");
            if (!testRoleEmployee)
            {
                IdentityRole role = new IdentityRole() { Name = "Employee" };
                allTest.Add(await _roleManager.CreateAsync(role));
            }
            //var user = new ApplicationUser()
            //{
            //    Email = "powerbit@gmail.com",
            //    UserName = "powerbit@gmail.com"
            //};
            //var check = await _userManager.CreateAsync(user, "123");
            //if (check.Succeeded)
            //{      
            //    allTest.Add(await _userManager.AddToRoleAsync(user, "Employee"));            
            //}
            return allTest;        
        }

        public async Task<List<IdentityResult>> DeleteAllRoleAsync(string email)
        { 
            List<IdentityResult> tempList = new List<IdentityResult>();
            if(email == "jalal@powerbit.com")
            {
                var tempy = await this.DeleteUserByEmailAsync(email);
                if (tempy.Succeeded)
                {
                    foreach (var item in _userManager.Users.ToList())
                    {
                        var tempUser = await this.DeleteUserByEmailAsync(item.Email);
                        if (tempUser.Succeeded)
                        {
                            tempList.Add(tempUser);
                        }
                    }
                    if (_userManager.Users.ToList().Count == 0)
                    {
                        //tempList.Add(tempy);            
                        foreach (var item in _roleManager.Roles.ToList())
                        {
                            var role = await _roleManager.FindByNameAsync(item.Name);
                            var testDelete = _roleManager.DeleteAsync(role).Result;
                            if (testDelete.Succeeded)
                            {
                                tempList.Add(testDelete);
                            }
                        }
                    }
                }

            }

            return tempList;
        }

        public async Task<IList<string>> GetAllUserRoleAsync(PowerAccountingUser email)
        {
            return await _userManager.GetRolesAsync(email);
        }

        public async Task<PowerAccountingUser> GetUserByIdAsync(string id)
        {
            var temp= await _userManager.FindByIdAsync(id);
            if (temp != null)
            {
                return temp;
            }
            else
            {
                return null; ;
            }
            
        }

        public async Task<PowerAccountingUser> GetUserByEmailAsync(string email)
        {
            return await _userManager.FindByEmailAsync(email);
        }
        public async Task<IdentityResult> SetRoleToUserByMyRoleModelAsync(MyRoleModel roleModel)
        {
            return await _userManager.AddToRoleAsync(await this.GetUserByEmailAsync(roleModel.Email), roleModel.Role);
        }
        public async Task<IdentityResult> DeleteUserByEmailAsync(string email)
        {
            var userNow= await _userManager.FindByEmailAsync(email);
            var result= _userManager.DeleteAsync(userNow).Result;
            if (result.Succeeded)
            {
                return result;
            }
            return result;
        }

        public async Task<IdentityResult> CreateUserAsync(SignUpUserModel userModel,bool Flag)
        {
            var user = new PowerAccountingUser()
            {
                RefreshTokenExpiryTime=DateTime.Now,
                //   FirstName = userModel.FirstName,
                //  LastName = userModel.LastName,
                FullName=userModel.UserName,
                Email = userModel.Email,
                UserName = userModel.Email,
                EmailConfirmed=Flag
            };
            var result = await _userManager.CreateAsync(user, userModel.Password);
            if (result.Succeeded)
            {
               // await GenerateEmailConfirmationTokenAsync(user);               
            }
            return result;
        }

        public async Task GenerateEmailConfirmationTokenAsync(PowerAccountingUser user)
        {
            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            if (!string.IsNullOrEmpty(token))
            {
                 await SendEmailConfirmationEmail(user, token);   
            }
           
        }

        public async Task GenerateForgotPasswordTokenAsync(PowerAccountingUser user)
        {
            var token = await _userManager.GeneratePasswordResetTokenAsync(user);
            if (!string.IsNullOrEmpty(token))
            {
                await SendForgotPasswordEmail(user, token);
            }
        }

        public async Task<SignInResult> PasswordSignInAsync(SignInModel signInModel)
        {
            return await _signInManager.PasswordSignInAsync(signInModel.Email, signInModel.Password, signInModel.RememberMe, true);
        }

        public async Task SignOutAsync()
        {
            await _signInManager.SignOutAsync();
        }

        public async Task<IdentityResult> ChangePasswordAsync(ChangePasswordModel model)
        {
            // var userId = _userService.GetUserId();
            // var user = await _userManager.FindByIdAsync(userId);
            var user = await _userManager.FindByEmailAsync(model.Email);
            return await _userManager.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword);
        }


        public async Task<IdentityResult> ConfirmEmailAsync(string uid, string token)
        {
            return await _userManager.ConfirmEmailAsync(await _userManager.FindByIdAsync(uid), token);
        }

        public async Task<IdentityResult> ResetPasswordAsync(ResetPasswordModel model)
        {
            return await _userManager.ResetPasswordAsync(await _userManager.FindByIdAsync(model.UserId), model.Token, model.NewPassword);
        }

        private async Task SendEmailConfirmationEmail(PowerAccountingUser user, string token)
        {
            string appDomain = _configuration.GetSection("Application:AppDomain").Value;
            string confirmationLink = _configuration.GetSection("Application:EmailConfirmation").Value;

            UserEmailOptions options = new UserEmailOptions
            {
                ToEmails = new List<string>() { user.Email },
                PlaceHolders = new List<KeyValuePair<string, string>>()
                {
                  //  new KeyValuePair<string, string>("{{UserName}}", user.FirstName),
                    new KeyValuePair<string, string>("{{Link}}",
                        string.Format(appDomain + confirmationLink, user.Id, token))
                }
            };

         //   await _emailService.SendEmailForEmailConfirmation(options);
        }

        private async Task SendForgotPasswordEmail(PowerAccountingUser user, string token)
        {
            string appDomain = _configuration.GetSection("Application:AppDomain").Value;
            string confirmationLink = _configuration.GetSection("Application:ForgotPassword").Value;

            UserEmailOptions options = new UserEmailOptions
            {
                ToEmails = new List<string>() { user.Email },
                PlaceHolders = new List<KeyValuePair<string, string>>()
                {
                //    new KeyValuePair<string, string>("{{UserName}}", user.FirstName),
                    new KeyValuePair<string, string>("{{Link}}",
                        string.Format(appDomain + confirmationLink, user.Id, token))
                }
            };

           // await _emailService.SendEmailForForgotPassword(options);
        }
    }
}
