namespace Universal;

public class Property(string name, Type type, object? value)
{
    public string Name { get; } = name;
    public Type TypeName { get; } = type;
    public object Value { get; } = value ??= "NULL";
}

public class ReflectionHelper
{
    public static IEnumerable<Property> FromatDitits<T>(T model) where T : notnull
    {
        foreach (PropertyInfo propertyInfo in model.GetType().GetRuntimeProperties())
            yield return new(propertyInfo.Name, propertyInfo.PropertyType, propertyInfo.GetValue(model));
    }

    public static Dictionary<string, object?>? GetProperties<T>(T t)
    {
        if (t == null)
            return default;
        PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
        if (properties.Length <= 0)
            return default;

        Dictionary<string, object?> ListStr = [];

        foreach (PropertyInfo item in properties)
        {
            string name = item.Name; //名称
            object? value = item.GetValue(t, null);  //值

            if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                ListStr.Add(name, value);
            else
                GetProperties(value);

        }
        return ListStr;
    }

    public static Dictionary<string, object?>? GetFields<T>(T t)
    {

        if (t == null)
            return default;

        FieldInfo[] fields = t.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

        if (fields.Length <= 0)
            return default;

        Dictionary<string, object?> ListStr = [];
        foreach (FieldInfo item in fields)
        {
            string name = item.Name; //名称
            object? value = item.GetValue(t);  //值

            if (item.FieldType.IsValueType || item.FieldType.Name.StartsWith("String"))
                ListStr.Add(name, value);
            else
                GetFields(value);
        }
        return ListStr;


    }
}