using Mall.WindowsService.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace Mall.WindowsService.Helper
{
    /// <summary>
    /// 地址帮助类
    /// </summary>
    public class PathHelper
    {
        /// <summary>
        /// 应用程序Bin目录
        /// </summary>
        public static string RootPath
        {
            get
            {
                return AppDomain.CurrentDomain.BaseDirectory;
            }
        }
    }

    /// <summary>
    /// 配置文件帮助类
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// 获取任务配置文件
        /// </summary>
        /// <returns></returns>
        public static IList<CommandModel> GetTaskConfig()
        {
            IList<CommandModel> list = new List<CommandModel>();
            //加载接口配置文件
            string settingPath = PathHelper.RootPath + @"\task.json";
            using (StreamReader sr = new StreamReader(settingPath))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    serializer.Converters.Add(new JavaScriptDateTimeConverter());
                    serializer.NullValueHandling = NullValueHandling.Ignore;
                    //构建Json.net的读取流  
                    JsonReader reader = new JsonTextReader(sr);
                    //对读取出的Json.net的reader流进行反序列化，并装载到模型中  
                    list = serializer.Deserialize<IList<CommandModel>>(reader);
                }
                catch (Exception ex)
                {
                    LogHelper.Write("加载配置文件" + ex.Message.ToString());
                }
            }
            return list;
        }

        /// <summary>
        /// 加载DLL文件
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> LoadAssembly()
        {
            Dictionary<string, object> assemblyDic = new Dictionary<string, object>();
            string path = PathHelper.RootPath;
            DirectoryInfo directoryInfo = new DirectoryInfo(path);
            if (directoryInfo.Exists)
            {
                //搜索dll文件
                FileInfo[] dllList = directoryInfo.GetFiles("*.dll");

                if (!object.Equals(dllList, null) && dllList.Length > 0)
                {
                    foreach (var item in dllList)
                    {
                        AssemblyName assemblyName = AssemblyName.GetAssemblyName(item.FullName);
                        Assembly ass = Assembly.Load(assemblyName);
                        foreach (var type in ass.ExportedTypes)
                        {
                            string fullName = type.FullName;
                            assemblyDic.Add(fullName, type);
                        }
                    }
                }
            }
            return assemblyDic;
        }
    }
}
