using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Performance.DtoModels;
using Performance.Infrastructure;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Performance.Api
{
    /// <summary>
    /// 过期限制
    /// </summary>
    public class ExpirationLimitMiddleware
    {
        private readonly RequestDelegate _next;

        public ExpirationLimitMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/api/function/limit"))
            {
                var response = new ApiResponse(ResponseType.OK, new
                {
                    ExpirationTime = FunctionLimit.Limit.ExpirationTime.ToString("yyyy-MM-dd"),
                    Remark = FunctionLimit.Limit.Remark,
                });
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonHelper.Serialize(response));
                return;
            }
            else if (FunctionLimit.Limit.ExpirationTime > DateTime.Now)
            {
                await _next.Invoke(context);
                return;
            }
            else
            {
                var response = new ApiResponse(ResponseType.Expiration, FunctionLimit.Limit.Remark);
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonHelper.Serialize(response));
            }
        }
    }
}
