using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using ZpcBulletinBoard.Models;

namespace ZpcBulletinBoard.Pages.User
{
    [Authorize]
    public class LogoutModel : PageModel
    {
        private readonly UserManager<IdentityApplicationUser> _userManager;
        private readonly SignInManager<IdentityApplicationUser> _signInManager;
        private readonly ILogger<LogoutModel> _logger;

        public LogoutModel(UserManager<IdentityApplicationUser> userManager, SignInManager<IdentityApplicationUser> signInManager, ILogger<LogoutModel> logger)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);

            await _signInManager.SignOutAsync();

            //_logger.LogInformation($"Logout: {user.Name} {user.Surname} - {user.Company.Title}");

            //if (returnUrl != null)
            //{
            //    return LocalRedirect(returnUrl);
            //}

            return RedirectToPage();
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            var user = await _userManager.GetUserAsync(User);

            await _signInManager.SignOutAsync();

            _logger.LogInformation($"Logout: {user.Name} {user.Surname}");
            
            if (returnUrl != null)
            {
                return LocalRedirect(returnUrl);
            }

            return RedirectToPage();
        }
    }
}
