using System;
using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Log;
using Siger.Middlelayer.Redis.RedisEntities;

namespace Siger.Middlelayer.Redis
{
    public partial class RedisCache
    {
        private const string LicenseHash = "Licenses";

        /// <summary>
        /// 判定服务是否正常
        /// </summary>
        /// <returns></returns>
        public void CheckRunning()
        {
            try
            {
                var licenses = Client.HGetAll(LicenseHash);
                if (licenses.Any())
                {
                    Logger.WriteLineInfo("monitor: redis service is running.");
                }
            }
            catch(Exception e)
            {
                Logger.WriteLineError("monitor: redis service is blocked, error : " + e);
            }
        }

        public IEnumerable<LicenseEntity> GetLicenses()
        {
            var licenses = new List<LicenseEntity>();
            var configs = Client.HGetAll(LicenseHash);
            foreach (var config in configs)
            {
                var cidpid = config.Key.Split('_');
                licenses.Add(new LicenseEntity
                {
                    Cid = cidpid[0].ToInt(),
                    Pid = cidpid[1].ToInt(),
                    License = config.Value
                });
            }

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

        public void AddLicenseEntity(LicenseEntity license)
        {
            var key = $"{license.Cid}_{license.Pid}";

            Client.HSet(LicenseHash, key, license.License);
        }

        public void DeleteLicenseEntity(string key)
        {
            Client.HDel(LicenseHash, key);
        }


        public string GetLicense(string key)
        {
            return Client.HGet(LicenseHash, key);
        }

    }
}
