using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ButcherFactory.Controls
{
  internal class JST2018SDataFormat : DataFormatBase
  {
    // 00007RX:  FF 43 78 40 00 10 00 00 00 37
    // 00009RX:  FF 43 88 40 00 10 00 00 00 37

    public override int DataLength
    {
      get { return 8; }
    }

    public override char Beginchar
    {
      get { return (char)0xFF; }
    }

    public override char Endchar
    {
      get { return (char)0x37; }
    }

    public override short Bufsize
    {
      get { return 8; }
    }

    public override string ParseData(string buf, out bool isStatic)
    {
      string weight;
      // 小数位数0-4
      int dot = (short)(0x07 & buf[1]) - 1;
      weight = CharTo16(buf[2]) + CharTo16(buf[3]) + CharTo16(buf[4]);

      weight = new string(weight.Reverse().ToArray());

      // insert dot
      weight = InsertDot(weight, dot);
      isStatic = true; // 默认 为 稳定


      // buffer[1] 符号位
      if (buf[5] == 0x01)
      {
        weight = (Convert.ToDecimal(weight) / 1000).ToString("#0.0000");
      }
      if ((buf[1] & 0x20) == 1)
        weight = "-" + weight;
      return weight;
    }

    string CharTo16(char c)
    {
      return ((int)c).ToString("x2");
    }

    public override bool ParseAscii(string buf, out string weight, out bool isStatic)
    {
      isStatic = false;
      weight = FindDataFrame(buf, DataLength);

      if (string.IsNullOrEmpty(weight))
      {
        return false;
      }

      weight = ParseData(weight, out isStatic);

      return true;
    }

    public override string FindDataFrame(string buf, int fSize)
    {
      var bufSize = buf.Length;
      if (fSize > bufSize)
      {
        return string.Empty;
      }

      int index = buf.IndexOf(Beginchar); // 查找开始字符的索引

      if (index < 0 || (index + fSize) > bufSize)
      {
        return string.Empty;
      }

      string data = buf.Substring(index, fSize);

      return data;
    }

    private static string InsertDot(string weight, int dotBits)
    {
      var rst = weight.Insert(weight.Length - dotBits, ".").Trim('0');
      if (rst.StartsWith("."))
        rst = "0" + rst;
      return rst;
    }

    public override bool ParseAscii(string buf, out string weight, out bool isStatic, out string subStr)
    {
      weight = "";
      isStatic = false;
      subStr = "";
      return false;
    }
  }
}
