using System;
using System.Linq;

namespace arDev
{
    public partial class Narumi 
    {
        public class Dataframe
        {
            public byte STX { get; private set; }
            public byte ETX { get; private set; }
            public byte[] Data { get; private set; }
            public string DataString { get; private set; }
            public byte[] checksum { get; private set; } = new byte[2];
            public bool Valid { get; private set; } = false;
            public string Message { get; private set; } = string.Empty;
            public byte[] Buffer { get; private set; }
            public string Cmd { get; private set; } = string.Empty;

            public bool Parse(byte[] data, int MinRecvLength = 0)
            {
                if (data == null || data.Any() == false)
                {
                    this.Message = string.Format("수신 데이터가 없습니다");
                    return false;
                }
                else if (data.Length < 5)
                {
                    this.Message = $"데이터의 길이가 5보다 작습니다 길이={data.Length}";
                    return false;
                }
                else if (MinRecvLength > 0 && data.Length < MinRecvLength)
                {
                    this.Message = $"데이터의 길이가 {MinRecvLength}보다 작습니다 길이={data.Length}";
                    return false;
                }
                else if (data[0] != 0x02 || data[data.Length - 1] != 0x03)
                {
                    this.Message = $"STX/ETX Error";
                    return false;
                }
                Buffer = new byte[data.Length];
                Array.Copy(data, Buffer, data.Length);
                STX = data[0];
                ETX = data[data.Length - 1];
                Array.Copy(data, data.Length - 3, checksum, 0, 2);

                Data = new byte[data.Length - 4];
                Array.Copy(data, 1, Data, 0, data.Length - 4);

                if (data.Length > 2) Cmd = System.Text.Encoding.Default.GetString(Data, 0, 3);

                this.DataString = System.Text.Encoding.Default.GetString(Data);


                Valid = true;
                return true;
            }
            public Dataframe(byte[] buffer = null, int minlen = 0)
            {
                if (buffer != null) Parse(buffer);
            }
        }

    }


}
