using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RFrameGenerate.Common
{
    public class LockManage
    {
        static LockManage()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 6 * 60 * 1000;
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }

        static void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lock (lock_object)
            {
                for (int i = Locks.Count - 1; i >= 0; i--)
                {
                    if ((DateTime.Now - Locks[i].LockDateTime > Ts_lock) && Locks[i].IsUser == false)
                    {
                        Locks.RemoveAt(i);
                    }
                }
            }
        }
        public static TimeSpan Ts_lock = new TimeSpan(0, 3, 0);
        public static System.Timers.Timer timer;
        static object lock_object = new object();
        static List<LockItem> Locks = new List<LockItem>();

        public static LockItem GetLock(string key)
        {
            lock (lock_object)
            {
                var lo = Locks.Where(a => a.Key == key).FirstOrDefault();
                if (lo == null)
                {
                    lo = new LockItem(key) { IsUser = true };
                    Locks.Add(lo);
                }
                return lo;
            }
        }

    }

    public class LockItem
    {
        public LockItem(string key)
        {
            this.Key = key;
            this.LockDateTime = DateTime.Now;
            this.IsUser = false;
        }
        public string Key { get; set; }
        public bool IsUser { get; set; }
        public DateTime LockDateTime { get; set; }

    }
}
