﻿using Microsoft.AspNetCore.Http;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Threading.Tasks;
using Wicture.DbRESTFul.Cache;

namespace Wicture.DbRESTFul.Auth
{
    public interface IApiAuthorizeFilter
    {
        event EventHandler<LoginEventArgs> OnLogin;

        event EventHandler<AuthorizationFailedEventArgs> OnAuthorizationFailed;

        event EventHandler<AuthorizationSucceededEventArgs> OnAuthorizationSucceeded;

        IdentityInfo OnAuthorization(HttpContext context, ConfiguredAPI api);

        IdentityInfo Identify(string token, ConfiguredAPI api, string from);

        void InvalidateToken(IdentityInfo identity);

        void EnableInvalidateToken(ICacheProvider cacheProvider);

        Task TokenRequest(HttpContext context, Func<Task> next);
        Task RefreshTokenRequest(HttpContext context, Func<Task> next);

        TokenValidationParameters ValidationParameters { get; set; }
        TokenProviderOptions ProviderOptions { get; set; }
        IAuthProvider AuthProvider { get; set; }
    }

    public class LoginEventArgs : EventArgs
    {
        public HttpContext HttpContext { get; set; }
        public bool Succeeded { get; set; }
        public string Token { get; set; }
        public IdentityInfo IdentityInfo { get; set; }
        public bool Refreshed { get; set; }
        public string Tag { get; set; }
        public LoginEventArgs(HttpContext context, IdentityInfo identityInfo, string token, string tag, bool succeeded, bool refreshed = false)
        {
            HttpContext = context;
            IdentityInfo = identityInfo;
            Token = token;
            Succeeded = succeeded;
            Refreshed = refreshed;
            Tag = tag;
        }
    }

    public class AuthorizationEventArgs : EventArgs
    {
        public ConfiguredAPI Api { get; set; }
        public HttpContext HttpContext { get; set; }
        public string Token { get; set; }
    }

    public class AuthorizationSucceededEventArgs : AuthorizationEventArgs
    {
        public IdentityInfo IdentityInfo { get; set; }
        public AuthorizationSucceededEventArgs(HttpContext context, ConfiguredAPI api, string token, IdentityInfo identityInfo)
        {
            HttpContext = context;
            Api = api;
            Token = token;
            IdentityInfo = identityInfo;
        }
    }

    public class AuthorizationFailedEventArgs : AuthorizationEventArgs
    {
        public string Code { get; set; }

        public AuthorizationFailedEventArgs(HttpContext context, ConfiguredAPI api, string token, string code)
        {
            HttpContext = context;
            Api = api;
            Token = token;
            Code = code;
        }
    }
}
