using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using InventoryTraker.Web.Attributes;
using InventoryTraker.Web.Core;
using InventoryTraker.Web.Identity;
using InventoryTraker.Web.Models;
using Microsoft.AspNet.Identity;

namespace InventoryTraker.Web.Controllers
{
    public class UserController : ControllerBase
	{
		private readonly ApplicationUserManager _userManager;
	    private readonly IMapper _mapper;

	    public UserController(ApplicationUserManager userManager, IMapper mapper)
	    {
		    _userManager = userManager;
		    _mapper = mapper;
	    }

	    public ActionResult Index()
		{
			return View();
		}

	    public JsonResult All()
	    {
		    var users =
				_userManager
				.Users
				.ProjectTo<UserViewModel>(_mapper.ConfigurationProvider)
				.OrderBy(u => u.UserName);

		    return BetterJson(users);
	    }
		
		[ActionLog]
		[HttpPost]
		public async Task<JsonResult> Create(UserEditForm form)
		{
			if (!ModelState.IsValid)
				return GetModelStateErrorListJson();

			var user = 
				new User
				{
					Email = form.Email,
					UserName = form.UserName,
				};

			var identityResult = await _userManager.CreateAsync(user, form.Password);

			if (!identityResult.Succeeded)
				return GetErrorListJson(identityResult.Errors.ToArray());

			return BetterJson(_mapper.Map<UserViewModel>(user));
		}

		[ActionLog]
		[HttpPost]
		public async Task<JsonResult> Edit(UserEditForm form)
		{
			if (!ModelState.IsValid)
				return GetModelStateErrorListJson();

			var user = _userManager.FindByEmail(form.Email);

			user.UserName = form.UserName;
			user.Email = form.Email;

			if (!string.IsNullOrEmpty(form.Password))
			{
				var resetResult = await _userManager.ChangePasswordAsync(user, form.Password);
				if (!resetResult.Succeeded)
					return GetErrorListJson(resetResult.Errors.ToArray());
			}

			var identityResult = _userManager.Update(user);

			if (!identityResult.Succeeded)
				return GetErrorListJson(identityResult.Errors.ToArray());

			return BetterJson(_mapper.Map<UserViewModel>(user));
		}
	}
}