using AspectCore.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using XYY.Core.Standard;
using XYY.Core.Standard.Data.Infrastructure;
namespace XYY.PerformanceCount.Standard
{
    public class MethodPerformanceAttrice : AbstractInterceptorAttribute
    {
        private string _methodName;

        public MethodPerformanceAttrice(string MethodName)
        {
            this._methodName = MethodName;
        }

        public override async Task Invoke(AspectContext context, AspectDelegate next)
        {
            IPerformanceDB db = null;
            try
            {
                db = context.ServiceProvider.GetService(typeof(IPerformanceDB)) as IPerformanceDB;
                if (db == null)
                    throw new Exception("当前实例未注册IPerformanceDB接口实现");
            }
            catch (Exception ex)
            {
                throw new Exception("当前实例未注册IPerformanceDB接口实现:" + ex.Message);
            }
            DateTime startTime = DateTime.Now;
            Stopwatch watch = new Stopwatch();
            watch.Start();
            string responseMessage = "OK";

            try
            {
                await next.Invoke(context);
            }
            catch (Exception ex)
            {
                responseMessage = ex.Message;
                throw ex;
            }
            finally
            {
                watch.Stop();
            }


            var methodPerformance = context.GetAttribute<MethodPerformanceAttrice>();
            MethodPerformanceModel menthodPerformance = new MethodPerformanceModel
            {
                StartTime = startTime,
                ExecutionTime = watch.ElapsedMilliseconds,
                MehtodName = this._methodName,
                RequestParameters = Newtonsoft.Json.JsonConvert.SerializeObject(context.Parameters),
                ResponseMessage = responseMessage,
                Id = Guid.NewGuid()
            };

            await db.AddLog(menthodPerformance);


        }
    }
}
