using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace YBDevice.NApi
{
    /// <summary>
    /// 检查是否在微信客户端中打开
    /// </summary>
    public class WeChatFilterAttribute : Attribute, IAsyncActionFilter
    {
        public bool Ignore { get; set; }
        public WeChatFilterAttribute(bool ignore = false)
        {
            Ignore = ignore;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (Ignore)
            {
                await next();
            }
            var useragent = context.HttpContext.Request.Headers["User-Agent"].ToString();
            if (string.IsNullOrEmpty(useragent) || !useragent.ToLower().Contains("micromessenger"))
            {
                context.Result = new ViewResult()
                {
                    ViewName = "outwechat"
                };
                return;
            }
            await next();
        }
    }
}
