using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Security.Cryptography;
using System.Text;

namespace UHFAPP.MultiDevice
{
    public class RFIDAPIManage
    {
        //第二步：定义断开回调委托
        internal static UHFAPP.UHFAPI.OnDisconnectCallback DisconnectCallback = null;
        private object _lock = new object();
        private Dictionary<string, RFIDAPI> _ht = new Dictionary<string, RFIDAPI>();

        private static RFIDAPIManage rfidAPIManage = new RFIDAPIManage();
        private RFIDAPIManage() {
            //第三步：给变量赋值
            DisconnectCallback = OnDisconnectCallback;
        }
       
        public static RFIDAPIManage GetInstance  {
            get { return rfidAPIManage; }
        }
        /// <summary>
        /// 获取设备
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public RFIDAPI GetDeviceByIP(string ip)
        {
            lock (_lock)
            {
                if (!_ht.ContainsKey(ip))
                {
                    _ht.Add(ip, new RFIDAPI(ip));
                }
                RFIDAPI obj = _ht[ip];
                return obj;

            }
        }
        /// <summary>
        /// 获取所有的设备
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, RFIDAPI> GetAllDevice()
        {
            lock (_lock)
            {
                return _ht;
            }
        }


        #region
        //第一步：定义断开回调函数
        private void OnDisconnectCallback(int id)
        {
            string ip = GetIpById(id);
            RFIDAPI rfid=GetDeviceByIP(ip);
            if (rfid != null)
            {
                rfid.RFIDDisconnectCallbank();
            }
            System.Console.WriteLine("OnDisconnectCallback id=" + id + "  ip="+ ip);

        }
        private string GetIpById(int id)
        {
            List<DeviceInfo> deviceList = UHFAPI.getInstance().LinkGetDeviceInfo();
            if (deviceList != null && deviceList.Count > 0)
            {
                for (int k = 0; k < deviceList.Count; k++)
                {
                    DeviceInfo deviceInfo = deviceList[k];
                    if (id == deviceInfo.Id)
                    {
                        return deviceInfo.Ip;
                    }
                }
            }
            return "";
        }
        #endregion
    }
}
