using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Collections.Concurrent;

namespace Common
{
    /// <summary>
    /// 基于MemoryCache的缓存辅助类
    /// </summary>
    public static class MemoryCacheHelper
    {
        private static readonly Object _locker = new object();
        public readonly static MemoryCache _cache = MemoryCache.Default;
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(MemoryCacheHelper));
        /// <summary>
        /// 缓存数据，默认2分钟后过期
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set(string key, object value)
        {
            if (value != null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();  //创建缓存项策略
                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(10)); //设定某个时间过后将逐出缓存
                Set(key, value, policy);
            }
        }
        public static void Delete(string key)
        {
            lock (_locker)
            {
                _cache.Remove(key);
            }
        }
        public static void SlideSet(string key, object value)
        {
            CacheItemPolicy policy = new CacheItemPolicy();  //创建缓存项策略
            policy.SlidingExpiration = new TimeSpan(0, 20, 0); //如果20分钟内使用，还使用这个数据
            Set(key, value, policy);
        }
        public static void SlideSet(string key, object value, TimeSpan span)
        {
            CacheItemPolicy policy = new CacheItemPolicy();  //创建缓存项策略
            policy.SlidingExpiration = span; //如果20分钟内使用，还使用这个数据
            Set(key, value, policy);
        }

        /// <summary>
        /// 缓存数据，指定过期时间
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiration"></param>
        public static void Set(string key, object value, DateTimeOffset expiration)
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.AbsoluteExpiration = expiration;
            //policy.RemovedCallback = new CacheEntryRemovedCallback((arguments) =>
            //{
            //    try
            //    {
            //        //第一版本的代码，先废弃掉
            //        string KKK = arguments.CacheItem.Key;
            //        if (KKK.StartsWith("UDPPackage_"))
            //        {
            //            object VVV = arguments.CacheItem.Value;
            //            string ti = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //            string nnn = Newtonsoft.Json.JsonConvert.SerializeObject(VVV);

            //            UDPPackageCount t = (UDPPackageCount)VVV;

            //            UDPPackage u = new UDPPackage();
            //            u.CommandType = KKK;
            //            u.TotalCount = t.Count;
            //            u.RemoveTime = ti;

            //            string mns = Newtonsoft.Json.JsonConvert.SerializeObject(u);
            //            logger.Error(ti + ",UDP Package：" + KKK + "," + nnn);
            //            CSRedisCacheHelper.redis3.Publish("redis-udppackage", mns);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        logger.Info("数量统计error：" + ex.Message);
            //    }
            //});
            Set(key, value, policy);
        }

        private static void Set(string key, object value, CacheItemPolicy policy)
        {
            if (value != null)
            {
                _cache.Set(key, value, policy);
            }
        }
        public static object Get(string key)
        {
            object result = _cache.Get(key);
            return result;
        }
        ///// <summary>
        ///// 获取缓存对象（主机的IP地址和端口），优先使用mac地址匹配
        ///// </summary>
        ///// <param name="key">主机编码</param>
        ///// <param name="mac">mac地址</param>
        ///// <returns></returns>
        //public static string Get(string key, string mac)
        //{
        //    object result = _cache.Get(mac);
        //    if (null == result)
        //    {
        //        result = _cache.Get(key);
        //    }
        //    return result == null ? "" : result.ToString();
        //}
        /// <summary>
        /// 判断主机是否在缓存里，优先使用mac地址匹配
        /// </summary>
        /// <param name="key">主机编码</param>
        /// <param name="mac">mac地址</param>
        /// <returns></returns>
        public static bool Contains(string key, string mac)
        {
            bool result = _cache.Contains(mac);
            if (!result)
            {
                return _cache.Contains(key);
            }
            return result;
        }
    }
}
