﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AstralTest.Models;
using AstralTest.ViewModels;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace AstralTest.Controllers
{
    [Authorize(Roles = "Admin")]
    [Route("Users")]
    public class UsersController : Controller
    {
        private readonly UserManager<User> _userManager;

        public UsersController(UserManager<User> userManager)
        {
            _userManager = userManager;
        }

        /// <summary>
        /// Create a new user
        /// </summary>
        [HttpPost]
        [Route("")]
        public async Task Create([FromBody]UserCreateView model)
        {
            if (ModelState.IsValid)
            {
                Mapper.Initialize(cfg => cfg.CreateMap<UserCreateView, User>()
                    .ForMember("UserName", opt => opt.MapFrom(src => src.Login)));
                var user = Mapper.Map<UserCreateView, User>(model);

                var result = await _userManager.CreateAsync(user, model.Password);

                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
        }

        /// <summary>
        /// Update user
        /// </summary>
        [HttpPut]
        [Route("{userGuid}")]
        public async Task Update(Guid userGuid, [FromBody]UserCreateView model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(userGuid.ToString());

                user.UserName = model.Login;
                user.Name = model.Name;

                var passwordValidator =
                    HttpContext.RequestServices.GetService(typeof(IPasswordValidator<User>)) as IPasswordValidator<User>;
                var passwordHasher =
                    HttpContext.RequestServices.GetService(typeof(IPasswordHasher<User>)) as IPasswordHasher<User>;

                if (passwordValidator != null)
                {
                    var result = await passwordValidator.ValidateAsync(_userManager, user, model.Password);
                    if (result.Succeeded)
                    {
                        user.PasswordHash = passwordHasher?.HashPassword(user, model.Password);
                        var updateResult = await _userManager.UpdateAsync(user);

                        if (!updateResult.Succeeded)
                        {
                            foreach (var error in result.Errors)
                            {
                                ModelState.AddModelError(string.Empty, error.Description);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Delete user
        /// </summary>
        [HttpDelete]
        [Route("{userGuid}")]
        public async Task Delete(Guid userGuid)
        {
            var user = await _userManager.FindByIdAsync(userGuid.ToString());
            if (user != null)
            {
                await _userManager.DeleteAsync(user);
            }
        }

        /// <summary>
        /// Get user
        /// </summary>
        [HttpGet]
        [Route("{userGuid}")]
        public async Task<UserGetView> GetUser(Guid userGuid)
        {
            Mapper.Initialize(cfg => cfg.CreateMap<User, UserGetView>()
                .ForMember("Login", opt => opt.MapFrom(src => src.UserName))
                .ForMember("Guid", opt => opt.MapFrom(src => src.Id)));
            var user = Mapper.Map<User, UserGetView>(await _userManager.FindByIdAsync(userGuid.ToString()));
            return user;
        }

        /// <summary>
        /// Get a list of users
        /// </summary>
        [HttpGet]
        [Route("")]
        public List<UserGetView> GetUsers()
        {
            var users = _userManager.Users.ToList();
            var models = new List<UserGetView>();

            foreach (var user in users)
            {
                Mapper.Initialize(cfg => cfg.CreateMap<User, UserGetView>()
                    .ForMember("Login", opt => opt.MapFrom(src => src.UserName))
                    .ForMember("Guid", opt => opt.MapFrom(src => src.Id)));
                var model = Mapper.Map<User, UserGetView>(user);
                models.Add(model);
            }
            return models;
        }
    }
}
