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

namespace Website.Controllers
{
  [AllowAnonymous]
  public class AccountsController : BaseController
  {
    private readonly UserManager<IdentityUser> _userManager;
    private readonly SignInManager<IdentityUser> _signinManager;

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

    public IActionResult Register()
    {
      return View(new RegisterViewModel());
    }

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

      var user = new IdentityUser(request.Username);
      var result = await _userManager.CreateAsync(user, request.Password);

      if (!result.Succeeded)
      {
        ModelState.AddModelError(nameof(RegisterViewModel.Username), "Une erreur est survenue");
        return View(request);
      }

      Success("Votre compte a bien été créé");

      return RedirectToAction("Login");
    }

    public IActionResult Login()
    {
      return View(new LoginViewModel());
    }

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

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

      if (!result.Succeeded)
      {
        ModelState.AddModelError(nameof(LoginViewModel.Username), "Une erreur est survenue");
        return View(request);
      }

      Success("Vous êtes désormais connecté !");

      return RedirectToAction(nameof(LinksController.Index), "Links");
    }

    public async Task<IActionResult> Logout()
    {
      await _signinManager.SignOutAsync();

      Success("Vous êtes désormais déconnecté !");

      return RedirectToAction(nameof(LinksController.Index), "Links");

    }
  }
}