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

namespace Len.Framework.Extensions
{
    public static partial class TypeExtensions
    {
        public static IEnumerable<Type> AllBaseAndImplementingTypes(this Type type)
        {
            return type.BaseTypes()
                .Concat(type.GetInterfaces())
                .SelectMany(ThisAndMaybeOpenType)
                .Where(t => t != type && t != typeof(object));
        }

        private static IEnumerable<Type> ThisAndMaybeOpenType(Type type)
        {
            yield return type;

            var typeInfo = type.GetTypeInfo();
            if (typeInfo.IsGenericType && !typeInfo.ContainsGenericParameters)
            {
                yield return type.GetGenericTypeDefinition();
            }
        }
    }
}
