using System;
using System.Collections;
using System.Text;
namespace Kreta.Framework.Exceptions
{
    /// 
    /// Kivételek segédosztálya.
    /// 
    public static class ExceptionUtil
    {
        /// 
        /// Ember számára olvasható karakterlánccá alakít egy kivételt.
        /// 
        /// A kivétel
        /// 
        /// A visszatérési érték tartalmazza a kivétel osztályának a nevét, a kivétel üzenetét, a kivétel vermét, és a belső kivételt.
        /// 
        public static string ExceptionToString(Exception exception)
        {
            if (exception == null)
            {
                return "";
            }
            StringBuilder builder = new StringBuilder();
            builder.Append(exception);
            for (Exception innerException = exception; innerException != null; innerException = innerException.InnerException)
            {
                if (innerException == exception)
                {
                    builder.Append(Environment.NewLine);
                    builder.AppendLine("Data:");
                }
                else
                {
                    builder.Append(Environment.NewLine);
                    builder.Append("Inner exception data:");
                }
                foreach (DictionaryEntry entry in exception.Data)
                {
                    string key = entry.Key.ToString();
                    if (key.StartsWith("$", StringComparison.OrdinalIgnoreCase)
                        ||
                        entry.Value == null)
                    {
                        continue;
                    }
                    builder.AppendFormat("{0}={1}", key, entry.Value);
                    builder.AppendLine();
                }
            }
            TypeLoadException typeLoadException = exception as TypeLoadException;
            // ReSharper disable once InvertIf
            if (typeLoadException != null)
            {
                builder.AppendFormat("Type: {0}", typeLoadException.TypeName);
                builder.AppendLine();
            }
            return builder.ToString();
        }
    }
}