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

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

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

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

		public JsonResult Get()
		{
			var user = _userManager.FindById(User.Identity.GetUserId());
			var model = _mapper.Map<ProfileForm>(user);
			return BetterJson(model);
		}

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

			var user = _userManager.FindById(User.Identity.GetUserId());
			user.Email = form.Email;
			user.UserName = form.UserName;

			if (!string.IsNullOrEmpty(form.NewPassword))
			{
				if (string.IsNullOrEmpty(form.CurrentPassword))
					return GetErrorListJson("Current password required");

				var result =
					await _userManager.ChangePasswordAsync(
						user.Id, form.CurrentPassword, form.NewPassword);

				if (!result.Succeeded)
					return GetErrorListJson(result.Errors.ToArray());
			}

			var identityResult = _userManager.Update(user);
			if (!identityResult.Succeeded)
				return GetErrorListJson(identityResult.Errors.ToArray());

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