using System.Collections;
using Quadarax.Foundation.Core.Reflection.Extensions;

namespace Quadarax.Foundation.Core.Object.Extensions
{
    public static class ObjectExt
    {
        public static IDictionary<string, object?> GetAllPropertyValues(this object? obj,string? indentPrefix = null)
        {
            var props = new Dictionary<string, object?>();
            if (obj == null)
                return props;

            if (string.IsNullOrEmpty(indentPrefix))
                indentPrefix = string.Empty;

            var type = obj.GetType();
            var propList = type.GetAllProperties();
            foreach (var prop in propList)
            {
                var val = prop.GetValue(obj, new object[] { });
                if (val is IEnumerable enumerable)
                {
                    var cnt = 0;
                    foreach (var item in enumerable)
                    {
                        var itemProps = item.GetAllPropertyValues(prop.Name + $"[{cnt}].");
                        foreach (var ip in itemProps)
                            props.Add(ip.Key, ip.Value);
                        cnt++;
                    }
                }
                else
                    props.Add(indentPrefix + prop.Name, val);
            }
 
            return props;
        }

    }
}
