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

using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Infrastructure.Utilities;
using System.Collections;
using Framework.Common;
using System.Collections.Concurrent;

namespace Framework.HandlerBase
{
	public class SessionCache
	{
		private static string _SessionFilePath = "";

		private volatile static ConcurrentDictionary<string, UserSession> _SessionDict = new ConcurrentDictionary<string, UserSession>();

		private static object locker = new object();

		static SessionCache()
		{
			_SessionFilePath = Path.Combine(ServiceContext.CurrentPath, "SessionCache.dat");
		}

		public static void Check()
		{
			foreach (KeyValuePair<string, UserSession> session in _SessionDict)
			{
				if (session.Value.IsTimeout)
				{
					Remove(session.Key);
				}
			}
		}

		public static void Add(UserSession session)
		{
			lock (locker)
			{
				if (!_SessionDict.ContainsKey(session.SessionId))
				{
					_SessionDict.AddOrUpdate(session.SessionId, session, (oldKey, oldValue) => session);
				}
			}
		}

		public static bool Exists(string sessionId)
		{
			return _SessionDict.ContainsKey(sessionId);
		}

		public static UserSession Get(string sessionId)
		{
			lock (locker)
			{
				if (Exists(sessionId))
				{
					return _SessionDict[sessionId];
				}
			}
			return null;
		}

		public static void Remove(string sessionId)
		{
			lock (locker)
			{
				if (Exists(sessionId))
				{
					UserSession session;
					_SessionDict.TryRemove(sessionId, out session);
				}
			}
		}

		public static List<UserSession> GetAllUser()
		{
			List<UserSession> list = _SessionDict.Values.ToList();
			return list;
		}

		public static UserSession GetSession(string loginAccount)
		{
			foreach (KeyValuePair<string, UserSession> kvp in _SessionDict)
			{
				if (kvp.Value.User.Account == loginAccount)
				{
					return kvp.Value;
				}
			}
			return null;
		}

		public static int Load()
		{
			if (!File.Exists(_SessionFilePath))
			{
				return 0;
			}

			byte[] buf = File.ReadAllBytes(_SessionFilePath);
			object obj = ObjectSerializer.Deserialize(buf);
			if (obj is Dictionary<string, UserSession>)
			{
				_SessionDict = obj as ConcurrentDictionary<string, UserSession>;
			}

			File.Delete(_SessionFilePath);
			return _SessionDict.Count;
		}

		public static void Save()
		{
			byte[] buf = ObjectSerializer.Serialize(_SessionDict);
			try
			{
				File.WriteAllBytes(_SessionFilePath, buf);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}

	}
}
