using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OpcServerHost
{
    public class ChatEventHelper
    {
        //定义一个静态对象用于线程部份代码块的锁定,用于lock操作
        private static Object syncObj = new Object();

        //定义用于把处理程序赋予给事件的委托。
        public delegate void ChatEventHandler(object sender, ChatEventArgs e);

        //创建一个静态Dictionary(表示键和值)集合(字典),用于记录在线成员,Dictionary<(Of <(TKey, TValue>)>) 泛型类
        public static Dictionary<string, ChatEventHandler> chatters = new Dictionary<string, ChatEventHandler>();

        //创建一个静态Dictionary存储设备的最新更新时间
        public static Dictionary<string, DateTime> chatterTimes = new Dictionary<string, DateTime>();

        public static Dictionary<string, string> machinegroups = new Dictionary<string, string>();

        //定义定时器,不断地检索客户端是否连接
        public static System.Timers.Timer dutyTimer;

        /// <summary>
        /// 开启定时器
        /// </summary>
        public static void StartListenClients()
        {
            dutyTimer = new System.Timers.Timer();
            dutyTimer.Interval = 500;
            dutyTimer.Elapsed += new System.Timers.ElapsedEventHandler(dutyTimer_Elapsed);
            dutyTimer.Start();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void dutyTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (syncObj)
            {
                foreach (string key in new List<string>(chatterTimes.Keys))
                {
                    if (chatterTimes[key].AddSeconds(5) < DateTime.Now)
                    {
                        chatters.Remove(key);
                        chatterTimes.Remove(key);
                    }
                }
            }
        }
    }

}