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

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

        public bool SetProductConfig(string key, QMSProductNameConfig config)
        {
            try
            {
                return Client.HSet(QMSProductNameConfig, key, JsonHelper.SerializerToJsonString(config));
            }
            catch
            {
                return false;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

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

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

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

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