﻿using System.Reflection;
using System.Text;

namespace NotekeeperAPI.Core.Exceptions
{
    public static class ExceptionHelper
    {
        public static string GetExceptionMessages(System.Exception ex)
        {
            var sb = new StringBuilder();
            GetExceptionMessage(ex, sb);
            return sb.ToString();
        }

        public static string GetStackTraces(System.Exception ex)
        {
            var sb = new StringBuilder();
            GetStackTrace(ex, sb);
            return sb.ToString();
        }

        public static void PreserveStackTrace(System.Exception ex)
        {
            var preserveStackTrace = typeof(System.Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
            preserveStackTrace.Invoke(ex, null);
        }

        private static void GetExceptionMessage(System.Exception ex, StringBuilder sb)
        {
            sb.AppendLine(ex.Message);
            if (ex.InnerException != null)
            {
                GetExceptionMessage(ex.InnerException, sb);
            }
        }

        private static void GetStackTrace(System.Exception ex, StringBuilder sb)
        {
            sb.AppendLine(ex.StackTrace);
            if (ex.InnerException != null)
            {
                sb.AppendLine(ex.StackTrace);
            }
        }
    }
}