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 QMSParameterListRepository : RedisRepositoryBase
    {
        private readonly bool _dispose;
        public QMSParameterListRepository(int companyId, int projectId, bool dispose = true) : base(companyId, projectId)
        {
            _dispose = dispose;
        }

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

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

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

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