namespace XUnitWebApi.SharedUtils
{
    public static class TestHelper
    {
        public static IEnumerable<Type> GetAllRepositories(string namespaceName = "DAL.Repositories")
        {
            var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
            .Where(t => t.IsClass && !t.Name.StartsWith("<")
            && (t.Namespace == namespaceName || t.Namespace == "DAL.SharedRepositories")
            );
            return types;
        }

        public static dynamic GetApiController_BasedOn_BaseController(string controllerName, dynamic repository)
        {
            var typeList = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                .Where(t => t.IsClass && !t.Name.StartsWith("<"))
                .Where(t => t.Name.Contains("Controller"))
                .Where(t => t.BaseType.Name.StartsWith("BaseController"))
                .Where(t => controllerName == "" || t.Name == controllerName + "Controller");
            //var entityTypes = typeList.ToList();
            //var entityType = entityTypes.Where(t => controllerName == "" || t.Name.Contains(controllerName)).FirstOrDefault();
            var entityType = typeList.FirstOrDefault();
            if (entityType == default) return default;
            Type type = entityType as Type;
            dynamic instance = Activator.CreateInstance(type, new object[] { repository });

            return instance;
        }

        public static dynamic GetRepository_BasedOn_BaseRepository(string repositoryName)
        {
            var typeList = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                .Where(t => t.IsClass && !t.Name.StartsWith("<"))
                .Where(t => repositoryName == "" || t.Name == repositoryName + "Repository")
                .Where(t => t.Name.Contains("Repository"))
                .Where(t => t.BaseType.Name.StartsWith("BaseRepository"));
            var entityType = typeList.FirstOrDefault();
            if (entityType == default) return default;
            Type type = entityType as Type;
            dynamic instance = Activator.CreateInstance(type);

            return instance;
        }
    }
}