﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin;
using Server.DAL.Abstract;
using Server.DAL.Entities;

namespace Server.WebApi.Infrastructure
{
    public static class OAuthExtensions
    {
        public static async Task<User> GetUser(this IOwinContext ctx)
        {
            IDbUsersRepository repository =
                (IDbUsersRepository) GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(
                    IDbUsersRepository));

            Claim claimUserId = ctx.Authentication.User.Claims.FirstOrDefault(c => c.Type == "UserID");

            if (claimUserId == null)
            {
                return null;
            }

            int id = Convert.ToInt32(claimUserId.Value);

            return await repository.Users.FirstOrDefaultAsync(x => x.UserId == id);
        }

        public static int? GetUserId(this IOwinContext ctx)
        {
            Claim claimUserId = ctx.Authentication.User.Claims.FirstOrDefault(c => c.Type == "UserID");

            if (claimUserId == null)
            {
                return null;
            }

            int id = Convert.ToInt32(claimUserId.Value);

            return id;
        }
    }
}