namespace BWP.WinFormControl.WeightDataFormat
{
  public class Xk3190D10DataFormat : DataFormatBase {

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

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

    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, "-");
      } else { 
      
      }
      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 );
      subStr = "";
      if (string.IsNullOrEmpty(weight)) {
        return false;
      }

      weight = ParseData(weight, out isStatic);
       
      return true;
    }
  
    #region 1.3 验证int奇数偶数
    /// <summary>
    /// 1.3 验证int奇数偶数
    /// </summary>
    /// <param name="num"></param>
    /// <returns></returns>
    public bool isJO(int num) {
      int a = num % 2;
      if (a == 0)
        return true;
      else
        return false;
    }
    #endregion
  }
}