using System.Collections;
using System.Reflection;
using PowerEasy.WebFuture.DataMigrations.Foundation.Log;

namespace PowerEasy.WebFuture.DataMigrations.Foundation.MigrationProgramme
{
    /// <summary>
    /// 迁移方案帮助类。
    /// </summary>
    public class MigrationProgrammeHelper
    {
        private static List<IMigrationProgramme> migrationProgrammeList;

        /// <summary>
        /// 迁移方案实例集合。
        /// </summary>
        public static List<IMigrationProgramme> MigrationProgrammeList
        {
            get
            {
                if (migrationProgrammeList == null)
                {
                    migrationProgrammeList = LoadMigrationProgramme();
                }

                return migrationProgrammeList;
            }
        }

        /// <summary>
        /// 获取迁移方案ComboBox控件数据源。
        /// </summary>
        /// <returns>返回迁移方案ComboBox控件数据源。</returns>
        public static ArrayList GetMigrationProgrammeDataSource()
        {
            var migrationProgrammeDataSource = new ArrayList();
            migrationProgrammeDataSource.Add(new DictionaryEntry("Select", "请选择迁移方案"));

            foreach (var item in MigrationProgrammeList)
            {
                migrationProgrammeDataSource.Add(new DictionaryEntry(item.MigrationProgrammeIdentifier, item.MigrationProgrammeName));
            }

            return migrationProgrammeDataSource;
        }

        /// <summary>
        /// 通过迁移方案标识符获取对应迁移方案实例。
        /// </summary>
        /// <param name="migrationProgrammeIdentifier">迁移方案标识符</param>
        /// <returns>返回迁移方案实例。</returns>
        public static IMigrationProgramme GetMigrationProgrammeByIdentifier(string migrationProgrammeIdentifier)
        {
            return MigrationProgrammeList.FirstOrDefault(x => x.MigrationProgrammeIdentifier == migrationProgrammeIdentifier);
        }

        /// <summary>
        /// 加载迁移方案。
        /// </summary>
        private static List<IMigrationProgramme> LoadMigrationProgramme()
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            var migrationProgrammeList = new List<IMigrationProgramme>();

            foreach (var type in types)
            {
                if (type.IsClass && type.GetInterfaces().Contains(typeof(IMigrationProgramme)))
                {
                    try
                    {
                        var instance = Activator.CreateInstance(type) as IMigrationProgramme;
                        migrationProgrammeList.Add(instance);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog($"加载迁移方案异常，异常迁移方案类型：{type.Name}，{ex.ToString()}");
                    }
                }
            }

            return migrationProgrammeList;
        }
    }
}
