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

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

        public void Dispose()
        {
            Client?.Dispose();
        }
        public void Add(ToolMS obj)
        {
            try
            {
                Client.HSet(HashToolMS, GetKey(obj), JsonConvert.SerializeObject(obj.node));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }

        public void DeleteChangeToolsRecord(string key)
        {
            try
            {
                Client.HDel(HashToolMS, key);
            }
            catch
            {
                throw;
            }
            finally
            {
                Client?.Dispose();
            }
        }

        private string GetKey(ToolMS obj)
        {
            return $"{obj.mid}_{obj.spindle}_{obj.tool}_{obj.pn}";
        }

        public ToolReferenceSample GetToolReferenceSample(string key)
        {
            try
            {
               var data= Client.HGet(HashTMSProcessLabeling, key);
                if (!string.IsNullOrEmpty(data))
                {
                    return JsonHelper.DeserializerJsonResult<ToolReferenceSample>(data);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
            return null;
        }
        public void AddToolReferenceSampleResult(ToolRefrence obj,string key)
        {
            try
            {
                Client.HSet(HashTMSPLabelingResult, key, JsonConvert.SerializeObject(obj));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }
        public void DeleteToolReferenceSampleResult(string key)
        {
            try
            {
                Client.HDel(HashTMSPLabelingResult, key);
            }
            catch
            {
                throw;
            }
            finally
            {
                Client?.Dispose();
            }
        }
    }
}
