using Microsoft.Extensions.Options;
using StackExchange.Redis;

namespace Infrastructure.Cache
{
    /// <summary>
    /// 缓存redis实现
    /// </summary>
    public sealed class RedisCacheContext : ICacheContext
    {
        private ConnectionMultiplexer _conn { get; set; }
        private IDatabase iDatabase { get; set; }
        private IServer server { get; set; }

        public RedisCacheContext(IOptions<AppSetting> options)
        {
            _conn = ConnectionMultiplexer.Connect(options.Value.RedisConf.Conn);
            iDatabase = _conn.GetDatabase(options.Value.RedisConf.Database);
            // 175.27.168.120:6050,password=HopetryRedis1406
            var Conn = options.Value.RedisConf.Conn;
            var hostAndPort = Conn.Substring(0, Conn.IndexOf(",", StringComparison.Ordinal));
            server = _conn.GetServer(hostAndPort);
        }

        public override T Get<T>(string key)
        {
            RedisValue value = iDatabase.StringGet(key);
            if (!value.HasValue)
            {
                return default(T);
            }

            if (typeof(T) == typeof(string))
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            else
            {
                return JsonHelper.Instance.Deserialize<T>(value);
            }
        }

        public override bool Set<T>(string key, T t, DateTime expire)
        {
            if (typeof(T) == typeof(string))
            {
                return iDatabase.StringSet(key, t.ToString(), expire - DateTime.Now);
            }
            else
            {
                return iDatabase.StringSet(key, JsonHelper.Instance.Serialize(t), expire - DateTime.Now);
            }
        }

        public override bool Remove(string key)
        {
            return iDatabase.KeyDelete(key);
        }

        public override Task<T> Lock<T>(string id, Func<string, Task<T>> func, string key = "hc")
        {
            return func(id);
        }

        /// <summary>
        /// HSET - 将哈希表 key 中的字段 field 的值设为 value。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="field">字段</param>
        /// <param name="value">值</param>
        public void HashSet<T>(string key, string field, T value)
        {
            iDatabase.HashSet(new RedisKey(key),
                new[] { new HashEntry(new RedisValue(field), new RedisValue(value.ToString() ?? string.Empty)) });
        }

        /// <summary>
        /// HGET - 获取哈希表中的指定字段的值。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="field">字段</param>
        /// <returns>字段对应的值</returns>
        public object HashGet(string key, string field)
        {
            return iDatabase.HashGet(key, field);
        }

        /// <summary>
        /// HEXISTS - 查看哈希表中是否存在指定字段。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="field">字段</param>
        /// <returns>是否存在</returns>
        public bool HashCheck(string key, string field)
        {
            return iDatabase.HashExists(key, field);
        }

        /// <summary>
        /// HDEL - 删除一个或多个哈希表字段。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="fields">要删除的字段数组</param>
        /// <returns>移除数量</returns>
        public long HashDel(string key, string[] fields)
        {
            var redisFields = fields.Select(f => new RedisValue(f)).ToArray();
            return iDatabase.HashDelete(new RedisKey(key), redisFields);
        }

        /// <summary>
        /// HLEN - 获取哈希表中字段的数量。
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>字段数量</returns>
        public long HashLen(string key)
        {
            return iDatabase.HashLength(key);
        }


        /// <summary>
        /// EXPIRE - 为键设置过期时间（秒）。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="timeout">过期时间（秒）</param>
        /// <returns>是否设置成功</returns>
        public bool ExpireKey(string key, long timeout)
        {
            return iDatabase.KeyExpire(key, TimeSpan.FromSeconds(timeout));
        }


        /// <summary>
        /// GET - 获取键对应的值。
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>键对应的值</returns>
        public object Get(string key)
        {
            return iDatabase.StringGet(key);
        }


        /// <summary>
        /// EXISTS - 判断键是否存在。
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>是否存在</returns>
        public bool CheckExist(string key)
        {
            return iDatabase.KeyExists(key);
        }

        /// <summary>
        /// DEL - 删除键。
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>是否删除成功</returns>
        public bool Del(string key)
        {
            return CheckExist(key) && iDatabase.KeyDelete(key);
        }


        /// <summary>
        /// LLEN - 获取列表的长度。
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>列表长度</returns>
        public long ListLen(string key)
        {
            return iDatabase.ListLength(key);
        }

        public IEnumerable<RedisKey> GetAllKeys(string pattern)
        {
            return server.Keys(pattern: new RedisValue(pattern));
        }
        /// <summary>
        /// HSET - 异步设置哈希表中的多个字段。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="hashFields"></param>
        /// <param name="flags"></param>
        public void HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None)
        {
            iDatabase.HashSetAsync(key, hashFields, CommandFlags.None);
        }
        /// <summary>
        /// HGETALL - 异步获取哈希表中的所有字段和值。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public Task<HashEntry[]> HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
        {
           return iDatabase.HashGetAllAsync(key, CommandFlags.None);
        }
        /// <summary>
        /// Returns all the members of the set value stored at key
        /// </summary>
        /// <param name="key"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public Task<RedisValue[]> SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None)
        {
            return iDatabase.SetMembersAsync(key, CommandFlags.None);
        }
        public Task<bool> SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
        {
            return iDatabase.SetAddAsync(key, value, CommandFlags.None);
        }
        public Task<bool> SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None)
        {
            return iDatabase.SetRemoveAsync(key, value, CommandFlags.None);
        }
    }
}