using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using PositioningWebApp.Models.UserProfile;
using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;

namespace PositioningWebApp.Services
{
	public class Sign
	{
		public async Task In(UserProfile model, bool isPersistent, HttpContext httpContext)
		{
			// Initialization.  
			var claims = new List<Claim>();

			try
			{
				// Setting  
				claims.Add(new Claim(ClaimTypes.Name, model.FirstName));
				claims.Add(new Claim(ClaimTypes.Surname, model.Surname));
				claims.Add(new Claim(ClaimTypes.Email, model.Email));
				claims.Add(new Claim(ClaimTypes.UserData, model.ID.ToString()));
				var claimIdenties = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
				var claimPrincipal = new ClaimsPrincipal(claimIdenties);
				var authenticationManager = httpContext;

				// Sign In.  
				await authenticationManager.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimPrincipal, new AuthenticationProperties() { IsPersistent = isPersistent });
			}
			catch (Exception ex)
			{
				// Info  
				throw ex;
			}
		}

		public Task Off(HttpContext httpContext)
		{
			try
			{ 
				var authenticationManager = httpContext;
				// Sign Out.  
				return authenticationManager.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
			} catch (Exception ex)
			{
				throw ex;
			}
		}
	}
}
