using System.Diagnostics;
using Microsoft.Practices.Unity.InterceptionExtension;
using Serilog.Events;

namespace Mindmancer.Common.Logging.LoggingExtensions
{
    internal class LoggingCallHandler : ICallHandler
    {
        private readonly IMmLogger logger;
        public LoggingCallHandler(IMmLogger logger)
        {
            this.logger = logger;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var type = input.Target.GetType();

            using (logger.Scope(null, methodName: input.MethodBase.Name, containingType: type))
            {

                // Invoke the next behavior in the chain.
                var result = getNext()(input, getNext);
                

                if (result.Exception != null)
                {
                    logger.Verbose("ErrorInMethod", result.Exception, "Method {method} threw exception {exeption}", input.MethodBase.Name, result.Exception.Message);
                }

                return result;
            }

        }

        public int Order
        {
            get;
            set;
        }
    }
}