using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Quadarax.Foundation.Core.Reflection.Extensions
{
    public static class TypeExt
    {
        public static IEnumerable<MethodInfo> GetMethodsWithAttribute<TAttribute>(this Type type, bool bInherit)where TAttribute : System.Attribute
        {
            var methods = type.GetMethods();
            return methods.Where(x => x.IsDefined(typeof(TAttribute), bInherit)).ToArray();
        }

        public static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TAttribute>(this Type type, bool bInherit)where TAttribute : System.Attribute
        {
            var properties = type.GetProperties();
            return properties.Where(x => x.IsDefined(typeof(TAttribute), bInherit)).ToArray();
        }

        public static IList<PropertyInfo> GetAllProperties(this Type? type)
        {
            if (type == null)
                return new List<PropertyInfo>();

            var propList = new List<PropertyInfo>(type.GetProperties(BindingFlags.Instance | BindingFlags.Public)); //type.GetTypeInfo().DeclaredProperties;
            if (type.GetTypeInfo().BaseType != null)
            {
                var nestedProps = GetAllProperties(type.GetTypeInfo().BaseType);
                foreach (var prop in nestedProps)
                {
                    if (propList.Any(x=>x.Name == prop.Name)) continue;
                    propList.Add(prop);
                }
            }
            return propList;
        }

    }
}
