using System.Threading.Tasks;
using Infrastructure.Identity;
using Infrastructure.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers
{
  public class AccountController : BaseController
  {
    private readonly UserManager<User> _userManager;
    private readonly SignInManager<User> _signinManager;

    public AccountController(UserManager<User> userManager, SignInManager<User> signinManager)
    {
      _userManager = userManager;
      _signinManager = signinManager;
    }

    [AllowAnonymous]
    public IActionResult Register()
    {
      return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public async Task<IActionResult> Register(RegisterViewModel cmd)
    {
      if (!ModelState.IsValid)
      {
        return View(cmd);
      }

      var user = new User { UserName = cmd.Username };
      var result = await _userManager.CreateAsync(user, cmd.Password);

      if (!result.Succeeded)
      {
        ModelState.AddModelError(nameof(RegisterViewModel.Username), "could not register");
        return View(cmd);
      }

      Success("Your account was created, you can now login");

      return RedirectToAction(nameof(Login));
    }

    [AllowAnonymous]
    public IActionResult Login()
    {
      return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel cmd)
    {
      if (!ModelState.IsValid)
      {
        return View(cmd);
      }

      var result = await _signinManager.PasswordSignInAsync(cmd.Username, cmd.Password, true, false);

      if (!result.Succeeded)
      {
        ModelState.AddModelError(nameof(LoginViewModel.Username), "Could not sign you in, please retry");
        return View(cmd);
      }

      Success("You're now logged in");

      return Redirect("/");
    }

    public async Task<IActionResult> Logout()
    {
      await _signinManager.SignOutAsync();
      Success("You're now logged out");
      return Redirect("/");
    }
  }
}