//==============================================================
//  版权所有：深圳杰文科技
//  文件名：BizLockHandler.cs
//  版本：V1.0  
//  创建者：Jay  ( QQ： 85363208 )
//  创建时间：2017-11-28 16:18
//  创建描述：
//  修改者：
//  修改时间：
//  修改说明： 
//==============================================================

using System;
using System.Collections.Generic;
using System.Linq;
using Infrastructure.Utilities;

namespace Framework.HandlerBase
{
	public class BizLockHandler : BaseHandler
	{
		#region - LockInfo -

		private class LockInfo
		{
			public string Id
			{
				get;
				set;
			}

			public string LockedBy
			{
				get;
				set;
			}

			public DateTime LockedOn
			{
				get;
				set;
			}
		}

		#endregion

		private static readonly object _locker = new object();
		private static readonly List<LockInfo> _List = new List<LockInfo>();

		public string Lock(string id)
		{
			return Lock(id, false);
		}

		public string Lock(string id, bool force)
		{
			lock (_locker)
			{
				if (force)
				{
					LockInfo lockInfo = _List.FirstOrDefault(a => a.Id == id && a.LockedBy == ServiceContext.CurrentUserName);
					if (lockInfo != null)
					{
						return "";
					}
				}
				else
				{
					LockInfo lockInfo = _List.FirstOrDefault(a => a.Id == id);
					if (lockInfo != null)
					{
						//throw new ServiceException("数据已经被 {0} 在 {1} 锁定，资源ID：{2}", lockInfo.LockedBy, lockInfo.LockedOn.ToString("H:mm"), idValue);
						return "{0}（{1}）".Fmt(lockInfo.LockedBy, lockInfo.LockedOn.ToString("yyyy-MM-dd HH:mm"));
					}
				}

				_List.Add(new LockInfo()
				{
					Id = id,
					LockedBy = ServiceContext.CurrentUserName,
					LockedOn = DateTime.Now
				});

				return "";
			}
		}

		public void Unlock(Guid id)
		{
			lock (_locker)
			{
				_List.RemoveAll(a => a.Id == id.ToString());
			}
		}
	}
}
