using JiShe.CollectBus.Common.Extensions;
using JiShe.CollectBus.Protocol.Interfaces;
using Microsoft.Extensions.Logging;

namespace JiShe.CollectBus.Protocol.T37612012.Appendix
{
    /// <summary>
    /// 附录A.14数据格式
    /// </summary>
    class Appendix_A14 : IAnalysisStrategy<List<string>>
    {
        private readonly ILogger<Appendix_A14> _logger;

        public Appendix_A14(ILogger<Appendix_A14> logger)
        {
            _logger = logger;
        }
        public async Task<bool> ExecuteAsync(List<string> data, Action<dynamic>? result = null)
        {
            decimal value = 0.0000M;
            List<decimal[]> decimalDCBList = new List<decimal[]>();
            decimalDCBList.Add(new decimal[2] { 1000M, 10000M });
            decimalDCBList.Add(new decimal[2] { 10M, 100M });
            decimalDCBList.Add(new decimal[2] { 10M, 1M });
            decimalDCBList.Add(new decimal[2] { 1000M, 100M });
            decimalDCBList.Add(new decimal[2] { 100000M, 10000M });
            for (int i = 0; i < data.Count; i++)
            {
                int CalcType = i > 1 ? 2 : 1;
                value += GetByteDCD(data[i].HexTo4BinZero(), CalcType, decimalDCBList[i]);
            }
            result?.Invoke(value);
            return await Task.FromResult(true);
        }

        /// <summary>
        /// 附录A.14数据格式计算规则方法
        /// </summary>
        /// <param name="binString">二进制字符串</param>
        /// <param name="calcType">//计算类型,1为除法，2为乘法</param>
        /// <param name="bcd">除数数组</param>
        /// <returns></returns>
        private decimal GetByteDCD(string binString, int calcType, decimal[] bcd)
        {
            decimal result = 0.00000M;
            switch (calcType)
            {
                case 1: 
                    result = (binString.Substring(0, 4).BinToDec() / bcd[0]) + (binString.Substring(4, 4).BinToDec() / bcd[1]);
                    break;
                case 2: 
                    result = (binString.Substring(0, 4).BinToDec() * bcd[0]) + (binString.Substring(4, 4).BinToDec() * bcd[1]);
                    break;
            }
            return result;
        }
    }
}
