﻿namespace NetCreditHub.Web.Mvc.Auditing
{
    using System.Web;
    using System.Diagnostics;
    using System.Collections.Generic;
    using Web.Auditing;

    public class HubAuditFilterData
    {
        private const string AbpAuditFilterDataHttpContextKey = "__HubAuditFilterData";

        public Stopwatch Stopwatch { get; }

        public AuditInfo AuditInfo { get; }

        public HubAuditFilterData(
            Stopwatch stopwatch,
            AuditInfo auditInfo)
        {
            Stopwatch = stopwatch;
            AuditInfo = auditInfo;
        }

        public static void Set(HttpContextBase httpContext, HubAuditFilterData auditFilterData)
        {
            GetAuditDataStack(httpContext).Push(auditFilterData);
        }

        public static HubAuditFilterData GetOrNull(HttpContextBase httpContext)
        {
            var stack = GetAuditDataStack(httpContext);
            return stack.Count <= 0
                ? null
                : stack.Pop();
        }

        private static Stack<HubAuditFilterData> GetAuditDataStack(HttpContextBase httpContext)
        {
            var stack = httpContext.Items[AbpAuditFilterDataHttpContextKey] as Stack<HubAuditFilterData>;
            if (stack == null)
            {
                stack = new Stack<HubAuditFilterData>();
                httpContext.Items[AbpAuditFilterDataHttpContextKey] = stack;
            }

            return stack;
        }
    }
}