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

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

        public void Dispose()
        {
            Client?.Dispose();
        }
        /// <summary>
        /// 获取当前刀具信息
        /// </summary>
        /// <param name="machindId"></param>
        /// <returns></returns>
        public SetToolData GetToolData(int machineId, string toolNumber)
        {
            try
            {
                var key = $"{machineId}_{toolNumber}";
                var data = Client.HGet(TlmToolData, key);
                if (!string.IsNullOrEmpty(data))
                {
                    return JsonHelper.DeserializerJsonResult<SetToolData>(data);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
            return null;
        }
        /// <summary>
        /// 获取所有刀具信息
        /// </summary>
        /// <param name="machindId"></param>
        /// <returns></returns>
        public List<SetToolData> GetAllToolData()
        {
            try
            {
                var ret = new List<SetToolData>();
                var data = Client.HGetAll(TlmToolData);
                if (data.Any())
                {
                    foreach (var item in data.Values)
                    {
                        ret.Add(JsonHelper.DeserializerJsonResult<SetToolData>(item));
                    }
                }
                return ret;
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }
        /// <summary>
        /// 设置当前刀具信息
        /// </summary>
        public void SetToolData(SetToolData data)
        {
            try
            {
                var key = $"{data.MID}_{data.ToolNumber}";
                Client.HSet(TlmToolData, key, JsonHelper.SerializerToJsonString(data));
            }
            catch
            {
                throw;
            }
            finally
            {
                if (_dispose)
                {
                    Dispose();
                }
            }
        }
    }
}
