﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using ProductService.Auth;
using ProductService.Models;

namespace ProductService.Providers
{
    public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        private readonly IAccountProvider _accountProvider;

        public ApplicationOAuthProvider(IAccountProvider accountProvider)
        {
            _accountProvider = accountProvider;
        }

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            context.Validated();
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            if (!string.IsNullOrWhiteSpace(context.UserName)
                && _accountProvider.IsUserPresent(context.UserName)
                && _accountProvider.VerifyPassword(context.Password, context.UserName))
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Actor, context.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Role, _accountProvider.GetUserRole(context.UserName)));
                context.Validated(identity);

                return;
            }
            context.SetError("invalid_grant", "The user name or password is incorrect.");
        }
    }
}