using ProjectManagementSystem.Common.Extenions;
using ProjectManagementSystem.Common.Logger;
using ProjectManagementSystem.WebApi.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace ProjectManagementSystem.WebApi.Filters
{
    public class GlobalActionFilterAttribute : ActionFilterAttribute
    {
        private const string Key = "__action_duration__";

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var stopWatch = new Stopwatch();
            actionContext.Request.Properties[Key] = stopWatch;
            stopWatch.Start();
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionContext)
        {
            var stopWatch = actionContext.Request.Properties.ContainsKey(Key) ? actionContext.Request.Properties[Key] as Stopwatch : null;
            if (stopWatch != null)
            {
                stopWatch.Stop();
            }

            string log = $"{actionContext.Request.GetClientIpAddress()} {actionContext.Request.Method} {actionContext.Request.RequestUri} 【{stopWatch?.ElapsedMilliseconds}ms】" +
                $"{Environment.NewLine}{actionContext.Request?.Content?.ReadAsStringAsync().Result}" +
                $"{Environment.NewLine}{actionContext.Response?.Content?.ReadAsStringAsync().Result}";

            CLog.Instance.SystemLog.WirteDebugCaller(log);
        }

    }
}
