using System;
using System.Collections.Generic;
using VCommon.Logging;

namespace VCommon.VApplication.Auditing.Json
{
    public abstract class JsonApplicationServiceAuditInterceptorBase : ApplicationServiceAuditInterceptorBase
    {
        private static readonly JsonAuditLogSerializer JsonSerializer = new JsonAuditLogSerializer();

        private static string TryJsonSerialize(object obj)
        {
            try
            {
                return JsonSerializer.SerializeObject(obj);
            }
            catch (Exception e)
            {
                Logger.Error("Audit json serialize fail", e);
                return JsonSerializer.SerializeObject(obj?.ToString());
            }
        }

        protected override void WriteAuditLog(Guid? tenantId, Guid? userId, string serviceClassName, string serviceMethodName, IReadOnlyDictionary<string, object> input, object output, object exception)
        {
            WriteJsonAuditLog(tenantId, userId, serviceClassName, serviceMethodName,
                JsonSerializer.SerializeObject(input),
                JsonSerializer.SerializeObject(output),
                TryJsonSerialize(exception));
        }

        protected abstract void WriteJsonAuditLog(Guid? tenantId, Guid? userId, string serviceClassName, string serviceMethodName, string input, string output, string exception);
    }
}
