﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Filters;
using LocalLingua.Logic.Authentication;
using Microsoft.AspNet.SignalR.Hubs;

namespace LocalLingua.Web.Filters
{
    public class JwtAuthenticationFilter : Attribute,IAuthenticationFilter
    {
        public bool AllowMultiple { get; }
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var queryStringCollection = HttpUtility.ParseQueryString(context.ActionContext.Request.RequestUri.Query);
            var token = queryStringCollection["token"];
            string username;

            if (JwtManager.ValidateToken(token, out username))
                return Task.FromResult(0);
            else
                throw new NotAuthorizedException();

        }

        public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            return Task.FromResult(0);
        }

        protected Task<IPrincipal> AuthenticateJwtToken(string token)
        {
            string username;

            if (!JwtManager.ValidateToken(token, out username))
                return Task.FromResult<IPrincipal>(null);

            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username)
            };

            var identity = new ClaimsIdentity(claims, "Jwt");
            IPrincipal user = new ClaimsPrincipal(identity);

            return Task.FromResult(user);
        }
    }
}
