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

namespace AIStudio.Wpf.DiagramDesigner
{
    /// <summary>
    /// 
    /// </summary>
    public static class GlobalType
    {
        static GlobalType()
        {
            //string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
            //AllAssemblies = Directory.GetFiles(rootPath, "*.dll")
            //    .Where(x => AssemblyPattern.Any(y => new FileInfo(x).Name.Contains(y)))
            //    .Select(x => Assembly.LoadFrom(x))
            //    .Where(x => !x.IsDynamic)
            //    .ToList();

            //var refAssembyNames = Assembly.GetEntryAssembly().GetReferencedAssemblies();
            //foreach (var asslembyNames in refAssembyNames)
            //{
            //    Assembly.Load(asslembyNames);
            //}
 
            AllAssemblies = AppDomain.CurrentDomain.GetReferanceAssemblies().Where(x => x.FullName.StartsWith("AIStudio")).ToList();

            AllAssemblies.ForEach(aAssembly => {
                try
                {
                    AllTypes.AddRange(aAssembly.GetTypes());
                }
                catch
                {

                }
            });
        }

        public static List<Assembly> GetReferanceAssemblies(this AppDomain domain)
        {
            var list = new List<Assembly>();
            domain.GetAssemblies().ToList().ForEach(i =>
            {
                GetReferanceAssemblies(i, list);
            });
            return list;
        }
        static void GetReferanceAssemblies(Assembly assembly, List<Assembly> list)
        {
            assembly.GetReferencedAssemblies().ToList().ForEach(i =>
            {
                var ass = Assembly.Load(i);
                if (!list.Contains(ass))
                {
                    list.Add(ass);
                    GetReferanceAssemblies(ass, list);
                }
            });
        }


        /// <summary>
        /// 解决方案程序集匹配名
        /// </summary>
        public static readonly List<string> AssemblyPattern = new List<string> { "AIStudio" };

        /// <summary>
        /// 解决方案所有程序集
        /// </summary>
        public static readonly List<Assembly> AllAssemblies;

        /// <summary>
        /// 解决方案所有自定义类
        /// </summary>
        public static readonly List<Type> AllTypes = new List<Type>();
    }
}
