﻿using System;
using System.Linq;
using System.Net.Http;
using System.Security.Authentication;
using System.Web;
using System.Web.Http.Controllers;
using WebApp.Filters;
using WebApp.Persistence;
using WebApp.Persistence.Models;

namespace WebApp.Extensions
{
	public static class TokenExtensions
	{
		public static StateRecord GetToken(this HttpActionContext actionContext)
		{
			StateRecord state = null;
			var authorization = actionContext.Request.Headers.Authorization;
			var cookieToken = actionContext.Request.Headers.GetCookies()
				.Select(collection =>
					collection.Cookies.Where(cookie =>
						"tvts_token".Equals(cookie.Name, StringComparison.InvariantCultureIgnoreCase) &&
						cookie.Values.Count == 1 &&
						!String.IsNullOrEmpty(cookie.Value))
					.ToArray())
				.Where(collection => collection.Length > 0)
				.Select(collection => collection.FirstOrDefault())
				.FirstOrDefault();
			var token = String.Empty;

			if (authorization == null)
			{
				if (cookieToken != null)
					token = cookieToken.Value;
			}
			else if (authorization.Scheme != null && authorization.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase))
				token = authorization.Parameter;

			if (!String.IsNullOrEmpty(token))
			{
				state = MvcApplication.Dao.GetToken(token);

				if (state != null && state.ExpiresOn <= DateTime.UtcNow)
					state = null;
			}

			if (state != null)
			{
				SessionContext.Cookie = new HttpCookie("tvts_token", state.Token);
				SessionContext.AddCookie = cookieToken == null || !state.Token.Equals(cookieToken.Value, StringComparison.OrdinalIgnoreCase);
				SessionContext.State = state;
			}
			else if (cookieToken != null)
				SessionContext.RemoveCookie = true;

			return state;
		}
	}
}