using dodohold.core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;

namespace molilian.core
{
    /// <summary>
    /// Authorization 授权
    /// </summary>
    public class APIProvider : IAuthorizationProvider
    {
        public string Domain => "api";

        private static string _consumerKey = "consumerkey";
        private static string _consumerSecret = "0512ef0d33f0f7d6";
        AccessTokenCore tokenCore = new AccessTokenCore();



        /// <summary>
        /// 验证是否未授权
        /// </summary>
        /// <param name="request">客户请求的token和scope（域）</param>
        /// <param name="logicAttr">受访问的权限属性</param>
        /// <returns></returns>
        public bool Verified(ActionExecutingContext context, (string ticket, string domain) request, MyAuthorizeAttribute logicAttr)
        {
            if (string.IsNullOrEmpty(request.ticket)) { return false; }
            if (!string.IsNullOrEmpty(logicAttr.Domain) && !logicAttr.Domain.Equals(request.domain)) { return false; }

            IAccessTokenDTO accessToken = Get(request.domain, request.ticket);
            if (accessToken == null) { return false; }
            if (accessToken.ExpiresIn == 0) { return true; }
            DateTime expiresTime = (accessToken.create_time + accessToken.ExpiresIn).Convert2Datetime();
            if (expiresTime > DateTime.Now) { return true; }
            return false;
        }


        public IAccessTokenDTO Get(HttpContext context)
        {
            var (accessToken, domain) = context.GetAccessToken();
            return Get(domain, accessToken);
        }

        /// <summary>
        /// 获取token缓存(从内存缓存中)
        /// </summary>
        /// <param name="token">客户请求的token</param>
        /// <returns></returns>
        public IAccessTokenDTO Get(string domain, string ticket)
        {
            var accessToken = tokenCore.Get(domain, ticket);
            return accessToken;
        }
        public int Revoke(string domain, string ticket)
        {
            return tokenCore.Delete(domain, ticket);
        }

        public IAccessTokenDTO Create(long id, string key, string secret, string roles, string domain, string clientIp)
        {
            //TODO  暂时就一个客户端授权码，以后做成数据库的
            if (string.IsNullOrEmpty(key) || !key.Equals(_consumerKey)) { return null; }
            if (string.IsNullOrEmpty(secret) || !secret.Equals(_consumerSecret)) { return null; }

            AccessTokenDTO token = Generate(id, key, domain, clientIp);
            tokenCore.Create(token);
            return token;
        }

        public AccessTokenDTO Generate(long id, string accessKey, string domain, string clientIp)
        {
            DateTime now = DateTime.Now;
            AccessTokenDTO token = new AccessTokenDTO
            {
                AccessId = id,
                AccessKey = accessKey,
                create_time = now.Convert2UnixTimestamp(),
                ExpiresIn = 0,
                Domain = domain,
                ClientIp = clientIp,
                AccessTicket = $"{accessKey}|{domain}|{now}|{clientIp}".ToAES256()
            };
            return token;
        }
    }
}
