using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using parkMonitor.model;
using parkMonitor.server;

namespace parkMonitor.entity
{
    /// <summary>
    /// 设备工厂类
    /// </summary>
    class EquipmentSimpleFactory
    {
		public static readonly EquipmentSimpleFactory ins = new EquipmentSimpleFactory();
		public Dictionary<string, IEquipments> strDevDic = new Dictionary<string, IEquipments>();

        public void EquipmentsInit(List<string> list)
        {
            foreach (string equistr in list)
            {
                if (!strDevDic.ContainsKey(equistr))
                {
                    strDevDic.Add(equistr, CreateEquipment(equistr));
                }
            }
        }

        public IEquipments FindEquipment(string equistr)
        {
			IEquipments e;
            if (strDevDic.ContainsKey(equistr) && strDevDic.TryGetValue(equistr, out e))
                return e;
            else
                return null;
        }

        public IEquipments CreateEquipment(string equistr)
        {
			IEquipments equipments = null;
			//Equipments
			EquipmentsSection lstEqup = ConfigurationManager.GetSection("Equipments") as EquipmentsSection;
			if(lstEqup == null) {
				return null;
			}
			//Equipment
			EquipmentSection equSection = lstEqup[equistr] as EquipmentSection;
			if(equSection == null) {
				return null;
			}
			//class name
			string className = equSection.value;

			try {
				//反射创建类
				Type t = Type.GetType(className);
                if (t == null) { return null; }
				object instance = Activator.CreateInstance(t);
				equipments = instance as IEquipments;

				//save
				strDevDic[equistr] = equipments;
			} catch(Exception ex) {
				Debug.WriteLine(ex.ToString());
			}
            return equipments;
        }
    }
}