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

namespace Siger.Middlelayer.Redis.Repositories
{
    public class QMSParameterMaintainConfigRepository : RedisRepositoryBase
    {
        private readonly bool _dispose;
        public QMSParameterMaintainConfigRepository(int companyId, int projectId, bool dispose = true) : base(companyId, projectId)
        {
            _dispose = dispose;
        }

        public bool SetConfig(string key, QMSParameterMaintainConfig config)
        {
            try
            {
                return Client.HSet(QMSParameterMaintainConfig, key, JsonHelper.SerializerToJsonString(config));
            }
            catch(Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
                return false;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public Dictionary<string, QMSParameterMaintainConfig> GetAllCofigs()
        {
            try
            {
                var list = Client.HGetAll<QMSParameterMaintainConfig>(QMSParameterMaintainConfig);
                if (list.Any())
                {
                    return list;
                }
                return new Dictionary<string, QMSParameterMaintainConfig>();
            }
            catch
            {
                return new Dictionary<string, QMSParameterMaintainConfig>();
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public QMSParameterMaintainConfig GetSingleByKey(string key)
        {
            try
            {
                return Client.HGet<QMSParameterMaintainConfig>(QMSParameterMaintainConfig, key);
            }
            catch
            {
                return null;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public bool DeleteByKey(string key)
        {
            try
            {                
                return Client.HDel(QMSParameterMaintainConfig, key) > 0;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public void Dispose()
        {
            Client?.Dispose();
        }
    }
}
