using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Redis.RedisEntities;

namespace Siger.Middlelayer.Redis
{
    public partial class RedisCache
    {
        public const string DbNameConfigHash = "DBNameConfig";
        public DbNameConfig GetDbName(int cid, int pid)
        {
            var key = $"{cid}_{pid}";

            var config = Client.HGet(DbNameConfigHash, key);
            if (!string.IsNullOrWhiteSpace(config))
            {
                return JsonHelper.DeserializerJsonResult<DbNameConfig>(config);
            }
            return null;
        }

        public IEnumerable<DbNameConfig> GetDbNameConfigs()
        {
            var dbConfigs = new List<DbNameConfig>();
            var configs = Client.HGetAll(DbNameConfigHash);
            foreach (var config in configs)
            {
                dbConfigs.Add(JsonHelper.DeserializerJsonResult<DbNameConfig>(config.Value));
            }

            return dbConfigs.OrderBy(q => q.Cid);
        }

        public void AddDbNameConfig(DbNameConfig config)
        {
            var key = $"{config.Cid}_{config.Pid}";

            var json = JsonHelper.SerializerToJsonString(config);

            Client.HSet(DbNameConfigHash, key, json);
        }

        public void DeleteDbNameConfig(string key)
        {
            Client.HDel(DbNameConfigHash, key);
        }
    }
}
