﻿// Copyright (c) 2018 Nikolay Zahariev <zahasoft.com>. Licensed under the MIT License.

namespace Zahasoft.Guard.Controllers
{
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Localization;
    using Zahasoft.Guard.Translations;
    using Zahasoft.Guard.User;
    using Zahasoft.Guard.User.PasswordChange;

    /// <summary>
    /// Change password controller.
    /// </summary>
    [Route(ControllerRoute.UserPasswordChange)]
    public class UserPasswordChangeController : BaseController
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="UserPasswordChangeController"/> class.
        /// </summary>
        /// <param name="localizer">String localizer</param>
        /// <param name="action">Forgot password action</param>
        public UserPasswordChangeController(IStringLocalizer localizer, IPasswordChangeAction<UserModel> action)
        {
            Localizer = localizer;
            Change = action;
        }

        /// <summary>
        /// Gets string localizer.
        /// </summary>
        protected IStringLocalizer Localizer { get; }

        /// <summary>
        /// Gets forgot password action.
        /// </summary>
        protected IPasswordChangeAction<UserModel> Change { get; }

        /// <summary>
        /// Get operation.
        /// </summary>
        /// <returns>View</returns>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Post operation.
        /// </summary>
        /// <param name="request">Post request</param>
        /// <returns>View</returns>
        [HttpPost]
        public async Task<IActionResult> Index(PasswordChangeRequest request)
        {
            request.Email = User?.Identity?.Name;
            PasswordChangeResponse response = await Change.ApplyAsync(request);

            switch (response.Result)
            {
                case PasswordChangeResult.Successful:
                    ViewBag.SuccessMessage = Localizer[TKey.PasswordChangedSuccessfully];
                    break;
                case PasswordChangeResult.InvalidRequest:
                    break;
                default:
                    return RedirectToError();
            }

            return View(request);
        }
    }
}