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

namespace ButcherFactory.Controls
{
  internal class Xk3190A9DataFormat : DataFormatBase
  {

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

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

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

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

    public override string ParseData(string buf, out bool isStatic)
    {
      string weight;
      // 小数位数0-4
      int dot = (short)(0x0F & buf[8]);
      weight = buf.Substring(2, 6).Trim();

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

      // buffer[1] 符号位
      if (buf[1] == '-')
      {
        weight = weight.Insert(0, "-");
      }

      return weight;
    }

    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;
    }

    private static string InsertDot(string weight, int dotBits)
    {
      string str = weight.TrimStart(new[] {
                                            '0'
                                          });
      str = str.Trim();

      if (dotBits > 0)
      {
        //str = str.Insert(str.Length - dotBits, ".");
        if (string.IsNullOrEmpty(str))
        {
          str = "0";
          str = str.Insert(str.Length, ".");
          for (int i = 0; i < dotBits; i++)
          {
            str = str.Insert(str.Length, "0");
          }
        }
        else
          str = str.Insert(str.Length - dotBits, ".");
      }

      if (str.IndexOf(".") == 0)
      {
        str = str.Insert(0, "0");
      }

      return str;
    }

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

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

      weight = ParseData(weight, out isStatic);


      return true;
    }
    // 根据开始字符找出 一个完整的数据帧
    public string FindDataFrame(string buf, int fSize, out string subStr)
    {
      var bufSize = buf.Length;
      subStr = "";
      int index = buf.IndexOf(Beginchar); // 查找开始字符的索引

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

      string data = buf.Substring(index, fSize);
      subStr = buf.Substring(index + fSize);
      // 检查结束字符
      if (data[fSize - 1] != Endchar)
      {
        return string.Empty;
      }

      return data;
    }
  }
}
